Simple Lisp Case statement question - problem comparing to nil - functional-programming

I'm trying to use a case statement to make some code more readable. It seems to work as a series of if statements, but for some reason the case statement always accepts a comparison to nil even if it is not true. Can someone clarify why this behavior occurs?
Example:
> (case 'a
(nil nil)
(otherwise 'b))
NIL
> (case 'a
('a 'b)
(otherwise nil))
B
In the above example, the first instance returns nil, even though 'a clearly is not nil. Trying to do the same thing with if statements behaves as I would expect:
> (if (eq 'a nil) nil 'b)
B
> (if (eq 'a 'a) 'b nil)
B
I'm assuming there is some behavior about the case statement I do not understand. Any help would be appreciated.
Edit:
Just to clarify, I know that 'a won't be evaluated. I just mocked up this example to create a situation in which the target of the case statement was definitely NOT nil.
I'm using xlisp-plus, but I'm going to try a real clisp install and see if it behaves differently.
Edit (one more time):
Installed CLISP and it works fine there. Not really worth the trouble to investigate why xlisp is different. Thanks for the sanity check, everyone.

Each of the key specifications in a CASE may be either a list of literals or a single atom. However, CLtL says that the atom must not be NIL since it is ambiguous as to whether it is the literal NIL or an empty list. Use a list of NIL instead:
> (case 'a
((nil) nil)
(otherwise 'b))
B
> (case nil
((nil) nil)
(otherwise 'b))
NIL

Common Lisp expects for CASE the item to test to be an atom or a list of atoms. The test also is the function EQL.
(case 'a
(a 'b) ; EQL a
(otherwise 'foo))
(case 'a
((a b c) 'foo) ; EQL to one of a, b or c
(otherwise 'bar))
The quoted for only works by accident. Don't use it:
; don't use this:
(case 'a
('a 'foo) ; <- bad! , EQL to QUOTE or A
(otherwise 'bar))
Above is the same as:
; don't use this:
(case 'a
((quote a) 'foo) ; <- bad! , EQL to QUOTE or A
(otherwise 'bar))

i think that it depends on your LISP version.
I have LispWorks on Mac and my result :
CL-USER 2 : 1 > (case 'a
(nil nil)
(otherwise 'b))
B

Same here with SBCL:
CL-USER> (case 'a
(nil nil)
(otherwise 'b))
B
That said, 'a is a symbol and as such can never be nil.

The values in a case form are implicitly quoted lists of literals, so this:
(case 'a
((a) 'b)
(otherwise nil))
is what you want. otherwise should work (as others have said) -- try t instead.
BTW, when you used 'a the reader reads it as (quote a) which means that it will also choose it when the value is quote, for example:
(case 'quote
('a 'b)
(otherwise nil))

Related

confusing about (write 'a) (write #\a) (write-char #\a) (write-char 'a)

Using
(write 'a)
give result A, so I guess 'a is the same as #\A (representation of character A in Lisp). But
(write-char 'a)
give error *** - WRITE-CHAR: argument A is not a character. So what is 'a?
Using
(write #\a)
give result #\a so I guess, for write function, #\a is used as a string; but why not need put #\a in double quote, i.e "#\a".
I already read about write, write-char function at here and here; and hard to find expected results when searching with keywords lisp 'a
TL;DR: 'a is not a character.
Lisp has some basic datatypes:
String, e.g. "Hello, world!", the same as an array of characters
Character, e.g. #\A. A lisp implementation is allowed to have multiple types of character (eg Unicode and ascii), but most do not.
number, e.g. 1.5. These can be subdivided into fixnums, bignums, and various kinds of float, as well as subtypes like bit.
Symbols, e.g. 'a, sometimes written A. A symbol is basically a pointer to a string plus some extra information, and typically symbols are looked up (aka interned) in a hash table called a package, so that if two symbols look the same, they are equal as pointers. The lisp reader (ie parser) normally converts symbols to uppercase before interning them
Lisp code is made of lisp objects and normally a symbol is evaluated as a variable lookup, so if you try to write the symbol A with (write a) you get an error about A being undefined.
So how can one express the symbol A in lisp? Well there is a special quote operator:
CL-USER> (quote a)
A
The way lisp evaluates (quote x) is that it just returns whatever lisp object is in the source code x, so e.f. (quote (a b c)) evaluates to the list of the symbols A, B, and C
Finally, lisp has syntactic sugar 'x for (quote x), so '(a b c) is exactly the same as (quote (a b c))
CL-USER> (list 'quote (list 'a 'b 'c)
'(A B C)
Finally, the function write normally tries to write objects in lisp syntax. So you get:
CL-USER> (write "good")
"good"
"good"
Note one is the string written by write And one is the return value printed by the REPL.
CL-USER> (read-from-string "A")
A
CL-USER> (read-from-string "#\\A")
#\A
So you see that write Tried to format things in a way that they can be understood by read.
Characters, Symbols, ...
So what is 'a
'a is a shorter notation for (quote a). (quote a) evaluates to the symbol a.
so I guess, for write function, #\a is used as a string; but why not need put #\a in double quote, i.e "#\a".
No, #\a is a character object.
Read an intro book instead of the language reference
You might want to read an introductory Lisp book and not the more complex language reference. I'd recommend Paul Graham's book ANSI Common Lisp or Common Lisp: A Gentle Introduction to Symbolic Computation by David S. Touretzky. The latter is available for download.

Not null lexical environment for eval

How to evaluate some lisp code using eval in not null lexical environment ? I need this feature for proper interpolation functionality.
If you model your environment as bindings like those found in let:
((x 3) (y 2))
... then you can evaluate any form f with those bindings in place, like so:
(eval `(let ,e ,f))
This is the simplest case, but you can easily convert your data to fit this syntax. You can also bind functions, macros, etc. if needed.
Note that if you need values at runtime, then maybe dynamic bindings are better. You can use hash-tables, etc. but note that there is also the lesser-known PROGV special operator:
Among other things, progv is useful when writing interpreters for languages embedded in Lisp; it provides a handle on the mechanism for binding dynamic variables.
Although I think the OP knows the answer already, let me try to give a somewhat more descriptive solution, hoping more experienced lispers can point to mistakes I may make below:
As #coredump mentions, progv is an option as well as a let form in eval. Here is an example:
Let's create a list with some numbers and a cons that has a lambda form, bypassing the reader lambda conversion:
(setf list1 '(1
1
(lambda ()
(print a))))
we can eval:
(eval
`(let ((a 3))
;; statement after comma is turned to a function by the reader.
;; same effect with explicit (funcall (function ,(third list1)))
;; because of the (lambda ..) macro form
(funcall ,(third list1))))
3
3
Note that variable a above is lexical, not special.
now, with progv we can create special variables and eval will use them.
Let's first start with a mistake:
(progv '(a) '(4)
(funcall (function (third list1))))
Error: (THIRD LIST1) is not a valid argument for FUNCTION.
or similarly:
(progv '(a) '(4)
(funcall (third list1)))
Error: Argument to apply/funcall is not a function: (LAMBDA NIL (PRINT A)).
Then, let's evaluate or compile:
(progv '(a) '(4)
(funcall (eval (third list1))))
4
4
or
(progv '(a) '(4)
(funcall (compile nil (third list1))))
Warning in 246: A assumed special
4
4
Above is the behaviour I got with LispWorks 7.1. eval didn't give the warning for special assumption, because:
(eval (third list1))
#<anonymous interpreted function 40600009EC>
eval returned an interpreted function, not compiled. If we further compile, then we'll see the same warning:
(eval (third list1))
#<anonymous interpreted function 40600009EC>
(compile nil *)
;;;*** Warning in 248: A assumed special
To make things right with progv, since it creates special variables, change the function:
(setf list1 '(1
1
(lambda ()
(declare (special a))
(print a))))
(progv '(a) '(4)
(funcall (compile nil (third list1))))
4
4
Note that to make the example politically correct, as CLHS does in progv page, we should better use (progv '(*a*) '(4) ...) and the lambda function should be defined with the *a* variable.

In Common Lisp, how to test if variable is special?

I thought I would be able to find this through Google, SO, or the books I'm reading, but it is proving elusive.
In the implementation I'm learning with, I can do the following at the top-level:
(defvar *foo* 4)
(set 'bar 3)
If I then call (describe '*foo*) and (describe 'bar), I get a description saying that *foo* is special and bar is non-special (among other details).
Is there a function that takes a symbol variable as an argument and returns true or false if it is special? If so, is describe probably implemented in part by calling it?
Context: I'm learning Common Lisp, but at work I have a system with a dialect of Lisp similar to Common Lisp, but the describe function is unimplemented. There's sort of an XY thing going on here, but I'm also trying to grok Lisp and CL.
Many Common Lisp implementations provide the function variable-information in some system dependent package.
Here in SBCL:
* (require :sb-cltl2)
NIL
* (sb-cltl2:variable-information '*standard-output*)
:SPECIAL
NIL
((TYPE . STREAM))
This function was proposed as part of some other functionality to be included into ANSI CL, but didn't make it into the standard. Still many implementations have it. For documentation see: https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node102.html
A non-special variable's environment will be captured when you create a closure over it:
(let ((x 1))
(let ((f (lambda () x)))
(let ((x 2))
(eql 2 (funcall f)))))
;;=> NIL
A special variable's lexical environment will not:
(defvar *x*) ; *x* is special
(let ((*x* 1))
(let ((f (lambda () *x*)))
(let ((*x* 2))
(eql 2 (funcall f)))))
;;=> T
Using this approach, you could easily define a macro that will expand to code like the previous that will let you determine whether a symbol is globally proclaimed special:
(defmacro specialp (symbol)
(let ((f (gensym "FUNC-")))
`(let ((,symbol 1))
(let ((,f (lambda () ,symbol)))
(let ((,symbol 2))
(eql 2 (funcall ,f)))))))
(specialp x) ;=> NIL
(specialp *x*) ;=> T
Note that this isn't a function, it's a macro. That means that the macro function for specialp is getting called with the symbols X and *X*. This is important, because we have to construct code that uses these symbols. You can't do this with a function, because there'd be no (portable) way to take a symbol and create a lexical environment that has a lexical variable with that name and a lambda function that refers to it.
This also has some risks if you try to use it with certain symbols. For instance, in SBCL, if you try to bind, e.g., *standard-output* to something that isn't a stream or a stream designator, you'll get an error:
CL-USER> (specialp *standard-output*)
; in: SPECIALP *STANDARD-OUTPUT*
; (LET ((*STANDARD-OUTPUT* 1))
; (LET ((#:FUNC-1038 (LAMBDA # *STANDARD-OUTPUT*)))
; (LET ((*STANDARD-OUTPUT* 2))
; (EQL 2 (FUNCALL #:FUNC-1038)))))
;
; caught WARNING:
; Constant 1 conflicts with its asserted type STREAM.
; See also:
; The SBCL Manual, Node "Handling of Types"
;
; compilation unit finished
; caught 1 WARNING condition
Defining globals with set or setq is not supported. There are 2 common ways to define globals:
(defparameter *par* 20) ; notice the earmuffs in the name!
(defvar *var* 30) ; notice the earmuffs in the name!
All global variables are special. Lexically scoped variables (not special) are not possible to get described. E.g.
(let ((x 10))
(describe 'x)) ; ==> X is the symbol X
It describes not the lexical variable but the symbol representation. It really doesn't matter since you probably never need to know in run time since you know this when you're writing if it's a bound lexical variable or global special by conforming to the earmuffs naming convention for global variables.
I believe the only way to get this information at run time* is by either using an extension to CL, as Rainer noted, or to use eval.
(defun specialp (x)
(or (boundp x)
(eval `(let (,x)
(declare (ignorable ,x))
(boundp ',x)))))
(Defect warning: If the variable is unbound but declared to be a type incompatible with nil, this could raise an error. Thanks Joshua for pointing it out in his answer.)
* The macro approach determines which symbol it is checking at macro expansion time, and whether that symbol is lexical or special at compile time. That's fine for checking the status of a variable at the repl. If you wanted to e.g. print all of the special variables exported by a package, though, you would find that to use the macro version you would end up having to use eval at the call site:
(loop for s being the external-symbols of :cl-ppcre
when (eval `(specialp-macro ,s)) do (print s))

why (car ''(a b)) evaluated to 'quote?

I'm a beginner Scheme programmer and I want to enrich my knowledge in functional programming. I programm in DrRacket IDE. Recently I found some interesting piece of code:
(car ''(a b))
Output:
'quote
Can anyone explain me why is it evaluated in this way?
This is because ' is short for (quote ...). So,
(car ''(a b))
is actually
(car (quote (quote (a b))))
Which evaluates to:
'quote
As pointed out by Josh in the comments, The actual result is just quote And the REPL prints an expression that can evaluate to quote in this case 'quote or what is the same as seen above (quote quote).
Remember that 'x (for any expression x) is just shorthand for (quote x), so this code:
(car ''(a b))
Is equivalent to this one:
(car (quote (quote (a b))))
Now it's easy to see that you're evaluating the car of a list that looks like this:
'(quote (a b))
Which gets evaluated to this:
(list 'quote (list 'a 'b))
And if we take the car of the above line we'll get the symbol quote, which is precisely the result that you see printed.
It doesn't!
(car ''(a b))
Which is
(car (quote (quote (a b))))
What happens is that car get evaluated to #<procedure:car> and since it'a procedure every argument gets evaluated once before applying..
(quote (quote (a b))) ; ==> (quote (a b))
Now #<procedure:car> of (quote (a b)) is quote. It's not 'quote. I can prove it. Try wrapping it in display like this: (display (car ''(a b))). The output is just quote
So why do you see 'quote in racket interactions window?
Racket has a feature that you can tweak how data is displayed when the expression results that are not explicitly printed by your program. The standard depends on the language selected and for #!racket it's to not to display the data as is but something that you can evaluate and becomes the data. In the REPL you can evaluate the output and get the same since that mode is in effect.
You can change the behaviour if you choose Choose language in the bottom left select and press Show details. The part output syntax lets you choose amongst 4 ways to "display results" in the interactions window. print is the language default and write is the same you get as when you display the data and what is expected from most Scheme books.

Understanding data mode in Lisp, why are these expressions not the same?

Currently I am reading "Land of Lisp". In one of the recent code samples the author gave:
> (eq 'fooo 'FoOo)
T
to prove that the symbols are case-insensitive. A few pages later data mode is formally introduced.
However I fail to really understand the following. eq is a function, so its name is case-insensitive as well. Therefore I should be able to do this:
> (eq 'Eq 'EQ)
T
Great. That worked as expected. But what if I put this into a list in data mode? Keep in mind, I am just experimenting with something that's new for me.
> (eq '(Eq) '(EQ))
NIL
> (eq '('Eq) '('EQ))
NIL
Uhm. Okay? Why is that? I would have expected that if I put the same symbol into two lists, that the lists would be considered equal.
Now the question: does that mean that not the contents of the lists are compared, but the list "objects" themselves? What am I missing?
Symbols are Case-Sensitive
> (eq (print (intern "foo")) (print (intern "FOO")))
|foo| ; printed
FOO ; printed
==> NIL ; returned
The default reader is Case-Converting
(eq (read-from-string "foo") (read-from-string "FOO"))
==> T
However, you can make the reader case-preserving:
(let ((*readtable* (copy-readtable)))
(setf (readtable-case *readtable*) :preserve)
(eq (read-from-string "foo") (read-from-string "FOO")))
==> NIL
Please take a look at
Reader Algorithm
Effect of Readtable Case on the Lisp Reader
EQ compares for pointer identity
Common Lisp provides 4 equality predicates, you should use the right one for your needs:
(equal '(Eq) '(EQ))
==> T
(equal '('Eq) '('EQ))
==> T
eq compares for things to be exactly the same, think pointer equality. This is like == in Java, even logically equivalent data will be falsy.
The solution here is to use equal which just does the "intelligent" thing and compares the lists' elements
> (equal '(A) '(a))
T
Additionally symbols are case sensitive. But by default the reader (the thing that turns code into an AST) defaults to being case insensitive. You can notice this distinction with a function like intern.
Lisp symbols are case sensitive. And even the lisp reader is case sensitive. The only point is that when the reader reads a symbol it usually make it in uppercase. The easiest way to tell the reader that the case in important is to put it between the vertical lines.
> '|asd|def|ghj|
|asdDEFght|
> '|asd|
|asd|
> '|ASD|
ASD
> 'ASD
ASD
> (eq 'asd '|ASD|)
t
> (eq 'asd '|aSd|)
nil
The eq predicate check that the arguments are the same objects (similar to compare the pointers to variables in C)
> (defparameter *x* 1)
> (defparameter *y* 1)
> (eq *x* *y*)
nil
So when you write '(asd) in REPL the list with one element is created. And when you write it the second time another list is created and these lists are actually different objects.
> (defparameter *list1* '('qwe))
> (defparameter *list2* '('qwe))
> (eq *list1* list2*) ;this are 2 different objects
nil
> (setf (first *list1* 'def))
> *list1* ;this list has changed
(DEF)
> *list2* ;and this did not
(QWE)
> (setf *list1* *list2*) ;now they are just different names for one object
> *list1*
(QWE)
> (eq *list1* *list2*)
t
There are another ways how to compare objects (eq eql equal equalp =). It's better to read documentation and play with REPL to see the difference.
To complicate things a bit.
Let's say we have the following in a file. Then we compile and load that file.
(defparameter *a* '(1))
(defparameter *b* '(1))
Now we calculate:
(eq *a* *b*)
It is undefined if this is NIL or T. The Common Lisp compiler may detect that the lists are equal and set both variables to the same list - that is EQ then also would be true. Actually there are Common Lisp compilers which are doing this. Executing the two DEFPARAMETER forms in a *REPLone would usually expect that the Lisp system does not detect that and that(eq a *b*)isNIL`.
EQUAL compares structure and (eq *a* *b*) for our example is always T.

Resources