Reputation: 1203
I know 'cond' is based off 'if', but can 'cond' do everything 'if' can do? Thanks
Upvotes: 3
Views: 3030
Reputation: 15759
Yes. Any conditional
(if x y z)
using if
can be transformed into an equivalent conditional using cond
:
(cond (x y)
(t z))
For example, consider the following:
(if (= 1 2) (format t "crazy~%") (format t "sane~%"))
The above code can be transformed into:
(cond ((= 1 2) (format t "crazy~%"))
(t (format t "sane~%")))
Upvotes: 8
Reputation: 21
Depending on which lisp you're dealing with, if
and cond
are definitely not always interchangeable. Here's a test to find out. The results I give are from MIT's (2014) Scheme interpreter.
We may design a new-if
method made using cond
:
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
We may try the following with the old-if and the new-if:
(define (recursive-func a b)
(if (= a 0) b
(recursive-func a b)))
(recursive-func 0 1)
=> 1
And with new-if
:
(define (recursive-func a b)
(new-if (= a 0) b
(recursive-func a b)))
(recursive-func 0 1)
=> ;Aborting!: maximum recursion depth exceeded
Upvotes: 2
Reputation: 118601
"if" may well be implemented as a macro around "cond". "cond" is the actual "primitive" here, not "if".
Upvotes: 5