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?

+3


source to share


3 answers


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.

+4


source


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.

+6


source


  • (message (if (equal INPUT "a") "bar" "foo"))

  • You don't want to quote the first parameter case

    - that doesn't make sense. If you specify INPUT

    , then the evaluation result will be a symbol INPUT

    , always . And in this case it is case

    useless, since there is no more than one case (in this case, the case otherwise

    ).

    Testing for equality is always (using eql

    , but it is not) a string "a"

    and a character INPUT

    . This is always wrong, which is why you always see the message with the source code foo

    .

+2


source







All Articles