Search code examples
lispelisp

Elisp: how can I express else-if


In elisp, the if statement logic only allows me an if case and else case.

(if (< 3 5) 
  ; if case
    (foo)
  ; else case
    (bar))

but what if I want to do an else-if? Do I need to put a new if statement inside the else case? It just seems a little messy.


Solution

  • Nesting if

    Since the parts of (if test-expression then-expression else-expression) an else if would be to nest a new if as the else-expression:

    (if test-expression1
        then-expression1
        (if test-expression2
            then-expression2
            else-expression2))
    

    Using cond

    In other languages the else if is usually on the same level. In lisps we have cond for that. Here is the exact same with a cond:

    (cond (test-expression1 then-expression1)
          (test-expression2 then-expression2)
          (t else-expression2))
    

    Note that an expression can be just that. Any expression so often these are like (some-test-p some-variable) and the other expressions usually are too. It's very seldom they are just single symbols to be evaluated but it can be for very simple conditionals.