Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equal Operator in Common Lisp

Why does this:

(every (lambda (x) (equal "a" x)) "aaaaa")

and this:

(every (lambda (x) (equal "a" x)) "a")

return NIL, while this:

(every (lambda (x) (equal "a" x)) '("a" "a" "a" "a"))

returns T? I thought every worked on all sequences.

like image 751
fvrghl Avatar asked Nov 28 '22 14:11

fvrghl


2 Answers

You can always find it out yourself. A test is only a few seconds away if you use an interactive Lisp system:

CL-USER 1 > (every (lambda (x) (equal "a" x)) "a")
NIL

Above returns NIL.

Now use the Common Lisp function DESCRIBE to get the data described.

CL-USER 2 > (every (lambda (x)
                     (describe x)
                     (describe "a")
                     (equal "a" x))
                   "a")

#\a is a CHARACTER
Name                "Latin-Small-Letter-A"
Code                97
Bits                0
Font                0
Function-Key-P      NIL

So the value of x is a character. The character #\a.

"a" is a SIMPLE-BASE-STRING
0      #\a
NIL

The type of "a" is SIMPLE-BASE-STRING (here in LispWorks).

If you look at the definition of EQUAL, then you can see that a character and a string are never equal, because they are of different types.

CL-USER 3 > (equal #\a "a")
NIL
like image 69
Rainer Joswig Avatar answered Dec 05 '22 01:12

Rainer Joswig


Because in case 1 and case 2 you compare "a" and #\a, but in last case you compare "a" and "a". Strings' elements are chars, not other strings.

For example:

(every (lambda (x) (equal #\a x)) "aaaaa")
=> T

Another alternative is to coerce x to string:

(every (lambda (x) (equal "a" (string x))) "aaaaa")
like image 25
monoid Avatar answered Dec 05 '22 02:12

monoid