What do :+ and :or do on Scheme? - scheme

I'm trying to do my homework and hacking through some example code I saw this line:
[(:+ (:or VAR)) (token-VAR (string->symbol lexeme))]
This is from a lexical analyzer in a calculator;
Now I'm not really sure what either of this does, and I'm not particularly sure what this means exactly, but I'm pretty sure it has what I need to finish my homework. Searching hasn't gotten me any help so all help is great at this time. Thanks!

The sample code probably imported parser-tools using the : prefix (which is the recommended prefix in the parser-tools documentation. If that's the case, then :+ means "repetition one or more times" and :or matches any of the subpatterns (just VAR in this case).

Related

Can somebody give me a quick rundown on what the "#f()" syntax in Emacs-Lisp is doing?

Today, as I was once again traipsing through the Emacs Manual, I got a little tired and decided to pop into the Org Mode manual for something a little lighter, and I was reading about link handling, and ended up reading (and rereading) the Help documentation for 'org-file-apps.
Well, when I peeked at the related variable 'org-file-apps-windowsnt, I was surprised to see some syntax in its value that I didn't recognise.
To be clear, I've read the elisp manual virtually cover-to-cover, so while it's not uncommon for me to not feel comfortable with a particular bit of syntax, it's fairly rare these days that I don't recognise it at all.
The syntax in question is in the following expression
((remote . emacs)
(system . #f(compiled-function
(file path)
#<bytecode -0x47e8150df949387>))
(t . #f(compiled-function
(file path)
#<bytecode -0x47e8150df949387>)))
Specifically, the #f() syntax.
I tried searching across my Info manuals in Emacs, but only came up with entries related to colour values (e.g., #FFFFFF for white), next I tried DDG and Google, but since all generalised search engines have decided that even something quoted is subject to fuzziness, I haven't turned up anything there.
So, yeah, I'm just hoping somebody can explain the #f() syntax in this bit of Emacs-Lisp code, and what it's doing, and maybe why it's used. I assume it must have something to do with the use of compiled bytecode, but beyond that I'm stumped.
Apologies for what is no doubt a basic question that I've simply forgotten from reading the elisp manual, but searching, including that manual, is getting me nowhere.
I submitted Emacs bug #55853 for this, asking that the f#(...) syntax be documented.
The bug was closed as "fixed" with this explanation. Apparently this is not Lisp-readable syntax but is instead intended to be for human consumption as "pretty-printed" output. I leave it to you whether you think it serves that purpose well. This is the bug-closure explanation:
It's from:
(cl-defmethod cl-print-object ((object compiled-function) stream)
(unless stream (setq stream standard-output))
;; We use "#f(...)" rather than "#<...>" so that pp.el gives better results.
(princ "#f(compiled-function " stream)
I.e., it's from the "pretty" version of prin1, and is not meant to be
readable by the Lisp reader.
[Emacs maintainer Lars has] now mentioned this in the Special Read Syntax node in the lispref [he means the Elisp]
manual in Emacs 28.2.
In other words, this is apparently "special read syntax", i.e., Lisp reader syntax that's not readable by the Lisp reader but is meant to communicate something to humans.
That description "explains the syntax" - the idea behind it. But it doesn't really tell you what the syntax is supposed to communicate to users, i.e., how to read it as a human.
I'd guess it's trying to be a placeholder, in this case, for a (compiled) function that takes arguments FILE and PATH.
What the source code for the function is; what the function does (e.g., it's doc); or where it's defined -- nothing like that is conveyed in the "pretty"-print. And whether "compiled" there means byte-compiled or "native"-compiled also isn't made clear.
Hopefully someone else may be able to add more light with another answer here. And perhaps the 18.2 doc will make things more clear.

HtDP / Chpt. 5: How do I use "symbol=?"? (Scheme)

I'm currently working through HtDP on my own.
In Chapter 5 "Symbolic Information" is covered. The example in the text is:
(define (reply s)
(cond
[(symbol=? s 'GoodMorning) 'Hi]
[(symbol=? s 'HowAreYou?) 'Fine]
[(symbol=? s 'GoodAfternoon) 'INeedANap]
[(symbol=? s 'GoodEvening) 'BoyAmITired]))
That's all clear. However, the second exercise asks:
Exercise 5.1.2. Develop the function check-guess. It consumes two numbers, guess and target. Depending on how guess relates to target, the function produces one of the following three answers: 'TooSmall, 'Perfect, or 'TooLarge.
Frankly, I don't really see when or why "symbol=?" comes in here. My solution only uses "cond". [EDIT: Code removed due to a suggestion since it is a solution to a textbook exercise.]
According to the text, "symbol=?" consumes two symbols and returns either true or false, depending on whether they are identical or not.
I fear that I am now deep into the realm of the Dunning-Kruger effect, but I really don't see a way to implement this piece of code with the use of "symbol=?". "cond" is covered in Chapter 4, which is why I am now confused.
Any help is highly appreciated.
If you want to have a look at the chapter in HtDP, then please go here:
http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-8.html#node_sec_5.1
Unfortunately, the solutions are only accessible with a password.
use < and > to compare the numbers. You can't to use symbol=? for this.

Circumvent EVAL in SCHEME

Peter Norvig in PAIP says:
in modern lisps...eval is used less often (in fact, in Scheme there is
no eval at all). If you find yourself using eval, you are probably
doing the wrong thing
What are some of the ways to circumvent using eval in scheme? Arent there case where eval is absolutely necessary?
There are cases where eval is necessary, but they always involve advanced programs that do things like dynamically loading some code (eg, a servlet in a web server). As for a way to "circumvent" using it -- that depends on the actual problem you're trying to solve, there's no magic solution to avoiding eval except for ... eval.
(BTW, my guess is that PAIP was written a long time ago, before eval was added to the Scheme Report.)
He's wrong. Of course there is eval in Scheme.
You'll need eval in some very rare case. The case that comes into mind first is when you'll build program with a program and then execute it. This happens mainly with genetic algorithm for example. In this case you build a lot a randomized programs that you'll need to execute. Having eval in conjunction with code being data make lisp the easiest programming language to do genetic algorithm.
Having these properties comes at a great cost (in term of speed and size of your program) because you'll remove all possibility to do compile time optimization on the code that will be evaled and you must keep the full interpreter in your resulting binary.
As a result it is considered poor design to use eval when it can be avoided.
The claim that Scheme has no eval is inaccurate at least for the most recent versions of the Scheme standard (R5RS and later). Usually, what you want is a macro instead, which will generate code at compilation time.
It is true that eval should be avoided. For starters, I've never seen a satisfactory definition of how should it behave, for example:
What environment expressions should be evaluated in when no environment is passed?
When you do pass in an environment, how do those work? For example, the standards specify no way you can pre-bind a value in that environment object.
That said, I've worked with a Scheme application that uses eval to generate code dynamically at runtime for cases where the structure of the computation cannot be known at compilation time. The intent has been to get the Scheme system to compile the code at runtime for performance reasons—and the difficulty is that there is no standard way to tell a Scheme system "compile this code."
It should go without saying also that eval can be a huge security risk. You should never eval anything that doesn't have a huge wall of separation from user input. Basically, if you want to use eval safely, you should be doing so in the context of the code-generation phase of a compiler-like system, after you've parsed some input (using a comprehensively defined grammar!).
First, PAIP is written for Common Lisp, not Scheme, so I don't know that he'd say the same thing. CL macros do much the same thing as eval, although at compile time instead of run time, and there's other things you could do. If you'd show me an example of using eval in Common Lisp, I could try to come up with other methods of doing the same thing.
I'm not a Scheme programmer. I can only speak from Norvig's perspective, as a Common Lisp programmer. I don't think he was talking about Scheme, and I don't know if he knew or knows Scheme particularly well.
Second, Norvig says "you are probably doing the wrong thing" rather than "you're doing the wrong thing". This implies that, for all he knows, there's times when eval is the correct thing to use. In a language like C, I'd say the same thing about goto, although they're quite useful in some restricted circumstances, but most goto use is by people who don't know any better.
One use I've seen for 'eval' in scripting environments is to parameterize some code with runtime values. for instance, in psuedo-C:
param = read_integer();
fn = eval("int lambda(int x) {
int param = " + to_string(param) + ";
return param*x; }");
I hope you find that really ugly. String pasting to create code at runtime? Ick. In Scheme and other lexically scoped Lisps, you can make parameterized functions without using eval.
(define make-my-fn
(lambda (param)
(lambda (x) (* param x)))
(let* ([ param (read-integer) ]
[ fn (make-my-fn param ])
;; etc.
)
Like was mentioned, dynamic code loading and such still need eval, but parameterized code and code composition can be produced with first class functions.
You could write a scheme interpreter in scheme. Such is certainly possible, but it is not practical.
Granted, this is a general answer, as I have no used scheme, but it may help you nonetheless. :)

Thoughts on variable/function naming conventions

I've been coding on and off my whole life. I've mostly coded Perl, but also some Java, PHP, C, C++. I've even took a stab at Emacs Lisp, and I've done the occasional shell script. However, I've never actually engaged the subject to gain any kind of expertise – other things have had higher priorities for me. I don't consider myself to be really proficient in any language but Perl, and also now Haskell which I'm taking a course in right now.
Lately, I've been thinking about my style of coding. Not the style of the actual code; as a CS student I only do projects for fun or for school, which enables me to write what in my opinion is beautiful code almost always. One question in particular has been troubling me. It's a rather curious thing, but still something I would like to hear other opinions about.
Here's the thing: I find myself taking a fair amount of time to name my functions and variables to the most easily understood names I can possibly think of. Sometimes this task can be very tedious, even when not taking into account the difficulty of finding a variable name that conveys the meaning of a piece of code. For example, right now I'm making a function that looks like this.
This is Haskell code but the meaning should be quite clear. (It's exact meaning isn't that important so if you want to, just skip the code and read on.)
-- return the row with least number of Nothing values
bestRow :: [[Maybe Int]] -> Int -> Maybe (Int,Int)
bestRow [] _ = Nothing
bestRow (row:rows) thisIndex
| nextRow == Nothing && thisFilled > 8 = Nothing
| nextRow == Nothing = Just (thisIndex,thisFilled)
| thisFilled >= nextFilled = Just (thisIndex,thisFilled)
| thisFilled < nextFilled = nextRow
where thisFilled = length $ filter (/= Nothing) row
nextRow = bestRow rows (thisIndex + 1)
(nextIndex,nextFilled) = fromMaybe (-1,-1) nextRow
I couldn't decide on the variable names. The function did it's task well but it wasn't as clear as it could be. Once I settled on a solution, I spent 15 minutes on naming and renaming the variables. Should I go with curIndex, nextIndex || index, nextIndex || ind, indN etc? 15 minutes after I decided I was done, I realized this function wasn't needed after all: I found a much better solution to my problem. BOOM I had lost a lot of time simply cleaning code to no use to anyone, least of all to me. Or at least it felt that way.
This is something which has happened to me more than once, and is quite frustrating, mostly because it makes me feel dumb. What are your thoughts on this subject? Is this something you've experienced, something wrong with my way of doing things or simply something unavoidable?
Are there "perfect" variable names, or is it "ok" if they at least doesn't obfuscate your code?
Thanks,
Stefan Kangas
Read the book Clean Code by Robert C. Martin
One thing he goes into detail on is naming. Variable and function names should be as exact as possible. If you require a comment to describe it, the function is either doing too much, or the name can be clearer.
The goal, is to have code that reads like a story. Changing variable and function names and breaking them down into several functions or variables if necessary to achieve this goal.
Great book, worth every penny
Good names for variables and functions make understandable code. Good names should describe the intent and use of a variable or function. Bad names confuse other coders when it comes time to make changes.
Clarity is good in code.
I think its psychological, I always used to think my variables etc was unreadable to anyone but me even though I always placed comments in my code.
Whenever I had to go through code by someone else I was quite surprised at how I could easily read their code without having to read every single comment, the exact same thing happens when they read my code so clearly I'm doing a good job ;)
I think as long as your comments are meaningful and actually describe what a method does, what a variable is being used for you should be fine.
One tip is to always make sure your comments are up to date. I've seen code too many times where the comments for a method haven't changed, but the method code has.....it can be very confusing!

Is there a way to check if a label is already defined in LaTeX?

I edited the question after David Hanak's answer (thanks btw!). He helped with the syntax, but it appears that I wasn't using the right function to begin with.
Basically what I want is to let the compiler ignore multiple definitions of a certain label and just use the first. In order to do that, I thought I'd just do something like this:
\makeatletter
\newcommand{\mylabel}[1]{
\#ifundefined{#1}{\label{#1}}{X}
}
\makeatother
This does not work though, because the first option is always chosen (it doesn't matter if the label is defined or not). I think the \#ifundefined (and the suggested \ifundefined) only work for commands and not for labels, but I don't really know much about LaTeX. Any help with this would be great! Thanks!
Much later update:
I marked David Hanak's response as the correct answer to my question, but it isn't a complete solution, although it really helped me.
The problem is, I think but I'm no specialist, that even though David's code checks to see if a label is defined, it only works when the label was defined in a previous run (i.e. is in the .aux file). If two \mylabels with the same name are defined in the same run, the second will still be defined. Also, even if you manage to work around this, it will make LaTeX use the first label that you defined chronologically, and not necessarily the first in the text.
Anyway, below is my quick and dirty solution. It uses the fact that counters do seem to be defined right away.
\newcommand{\mylabel}[1]{%
\#ifundefined{c##1}{%
\newcounter{#1}%
\setcounter{#1}{0}%
}{}%
\ifthenelse{\value{#1} > 0}{}{%
\label{#1}%
\addtocounter{#1}{1}%
}%
}
I'm not sure if it is necessary to initialize the counter to 0, as it seems like a likely default, but I couldn't find if that was the case, so I'm just being safe.
Also, this uses the 'ifthen' package, which I'm not sure is necessary.
I am also not a LaTeX expert, however after one day of trying and searching the internet the following worked for me. I have used a dummy counter to solve the problem. Hopefully this helps, apparently not many people are looking for this.
\newcommand{\mylabel}[1]{
\ifcsname c##1\endcsname%
\else%
\newcounter{#1}\label{#1}%
\fi%
}
# is a special character in LaTeX. To make your declaration syntactically correct, you'll have to add two more lines:
\makeatletter
\newcommand{\mylabel}[1]{
\#ifundefined{#1}{\label{#1}}{X}
}
\makeatother
The first line turns # into a normal letter, the last line reverses its effect.
Update: You might also want to take a look at the "plain" \ifundefined LaTeX macro.
Update 2
Okay, I did some research to figure out the answer to the real problem. The thing is that defining a label does not create a macro by that name; it prepends a "r#" to it. So try the following:
\makeatletter
\newcommand{\mylabel}[1]{
\#ifundefined{r##1}{\label{#1}}{X}
}
\makeatother
For more technical details, refer to line 3863 of latex.ltx in your LaTeX distribution (where it says \def\newlabel{\#newl#bel r}).
By Victor Eijkhout, "TeX by Topic", p.143:
\def\ifUnDefinedCs#1{\expandafter\ifx\csname#1\endcsname\relax}
This can be used to check whether a label is defined; if not, the label is printed:
\newcommand{\myautoref}[1]{\ifUnDefinedCs{r##1}{\color{magenta}\IDontKnow\{#1\}}\else\autoref{#1}\fi}

Resources