In book 'land of lisp' I read
Because the case command uses eq for comparisons, it is usually used only for branching on symbol values. It cannot be used to branch on string values, among other things.
Please explain why?
In book 'land of lisp' I read
Because the case command uses eq for comparisons, it is usually used only for branching on symbol values. It cannot be used to branch on string values, among other things.
Please explain why?
On
Because (eq "foo" "foo") is not necessarily true. Each time you type a string literal, it may create a fresh, unique string. So when CASE is comparing the value with the literals in the cases with EQ, they won't match.
On
Two strings with the same content "foo" and "foo" are not EQL. CASE uses EQL as a comparison (not EQ as in your question). Usually one might want different tests: string comparison case and case insensitive, for example. But for CASE on cannot use another test. EQL is built-in. EQL compares for pointer equality, numbers and characters. But not string contents. You can test if two strings are the identical data objects, though.
So, two strings "FOO" and "FOO" are usually two different objects.
But two symbols FOO and FOO are usually really the same object. That's a basic feature of Lisp. Thus they are EQL and CASE can be used to compare them.
The other two excellent answers do answer the question asked. I will try to answer the natural next question - why does
caseuseeql?The reason is actually the same as in
C(where the correspondingswitchstatement uses numeric comparison): thecaseforms in Lisp are usually compiled to something likegoto, so(case x (1 ...) (2 ...) (3 ...))is much more efficient than the correspondingcond. This is often accomplished by compilingcaseto a hash table lookup which maps the value being compared to the clause directly.That said, the next question would be - why not have a
casevariant withequalhash table clause lookup instead ofeql? Well, this is not in the ANSI standard, but implementations can provide such extensions, e.g.,ext:fcasein CLISP.See also why
eqlis the default comparison.