Zel
Zel

Reputation: 11

Is there a nested if in lisp?

(if (> 10 5)
    (format t "First number is greater ~%"))
    
    (if (> 10 15) 
        (format t "First number is greater ~%")
        (format t "Second number is greater ~%"))
        
        (if (= 10 10)
        (format t "Both numbers are equal"))

Upvotes: 1

Views: 605

Answers (2)

Zel
Zel

Reputation: 11

I finally figured out.

(cond ((> 10 5)
    (format t "First numbers is greater. ~%")
    (< 10 15)
         (format t "Second number is greater. ~%")
         (= 10 10)
             (format t "Both numbers are equal. ~%")))

Upvotes: 0

user5920214
user5920214

Reputation:

The syntax of if in most Lisps is (if <test> <then> [<else>]) although there may be some variation: sometimes the <else> is mandatory, and in some older lisps there can be many forms for <else> (I think elisp is the only commonly-used lisp where that is the case now). So a nested if is simple:

(if a
    ...
  (if b
      ...
    (if c
        ...
      ...)))

This is annoying in terms of indentation, so there is a form called cond in which the above expression would be, in Common Lisp:

(cond
 (a ...)
 (b ...)
 (c ...)
 (t ...))

or in Scheme

(cond
 (a ...)
 (b ...)
 (c ...)
 (else ...))

cond has the nice feature that all the ...s can be many forms.

If you didn't have cond you could write it in terms of if: here's a version using Scheme's macros (actually Racket's: void is Racket I think), called kond:

(define-syntax kond
  (syntax-rules (else)
    [(_)
     (void)]
    [(_ (else form ...))
     (begin form ...)]
    [(_ (test form ...)
        more ...)
     (if test
         (begin form ...)
         (kond more ...))]))

Similarly, if you didn't have if you could write it in terms of cond: here's one called yf written in terms of kond using Scheme macros again:

(define-syntax yf
  (syntax-rules ()
    [(_ test result)
     (kond (test result))]
    [(_ test result otherwise)
     (kond (test result)
           (else otherwise))]))

Both of these may be variously buggy.

Historically, cond was the primitive I think.

Upvotes: 2

Related Questions