Case in elisp, How to compare with string?
(defun test:case (INPUT)
(case (quote INPUT)
("a" (message "bar"))
(otherwise (message "foo"))
))
(test:case "a")
I'm looking to get a case structure that compares "a" to INPUT and calls (message "foo")
. I can't seem to get the code above to call anything other than (message "foo")
.
Am I supposed to be doing something wrong?
source to share
You probably want to use cond
in this case. case
is compared using eql
, which will compare the actual objects. In this case, they will be two different lines and therefore always evaluate the proposal otherwise
.
Using cond you can specify which equality operator to use, for example:
(defun test:case (INPUT)
(cond
((equal INPUT "a") (message "bar"))
(t (message "foo"))))
(test:case "a")
Look at the elisp equality predicates available and how they behave.
source to share
If you have Emacs 24, this pcase
also works for string comparisons and may be more readable than a long expression cond
.
(defun test-case (input)
(message
(pcase input
("a" "bar")
("b" "baz")
("c" "quux")
(_ "foo"))))
The matching rules for are pcase
more complex, but also much more general and flexible than those case
similar to pattern matching in ML or Haskell.
source to share
-
(message (if (equal INPUT "a") "bar" "foo"))
-
You don't want to quote the first parameter
case
- that doesn't make sense. If you specifyINPUT
, then the evaluation result will be a symbolINPUT
, always . And in this case it iscase
useless, since there is no more than one case (in this case, the caseotherwise
).Testing for equality is always (using
eql
, but it is not) a string"a"
and a characterINPUT
. This is always wrong, which is why you always see the message with the source codefoo
.
source to share