Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elisp: how can I express else-if

Tags:

lisp

elisp

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.

like image 318
Cameron Avatar asked Nov 19 '16 15:11

Cameron


1 Answers

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.

like image 53
Sylwester Avatar answered Oct 17 '22 03:10

Sylwester