(define (search-for-primes start end)
(if (even? start)
(search-for-primes (+ start 1) end)
(cond ((< start end) (timed-prime-test start)
(search-for-primes (+ start 2) end)))))
This is part of an answer for SICP exercise 1.22 (see link at the bottom). Why is it that in the above code the guy is able to put two things after the cond condition ( (< start end) )? How does this manage to work?
If I even do (cond ((< 4 5) (< 4 3) (< 6 7))) in the terminal then that brings an error.
http://www.billthelizard.blogspot.com/2010/02/sicp-exercise-122-timed-prime-test.html
In cond
, after each condition there's an implicit begin
, so you can write any number of expressions afterwards, but only the value of the last one is returned as a value of that condition. In fact, your example works:
(cond ((< 4 5) (< 4 3) (< 6 7)))
=> #t
The above is equivalent to:
(cond ((< 4 5)
(begin
(< 4 3)
(< 6 7))))
What happened there? The condition (< 4 5)
was evaluated to #t
, then (< 4 3)
was evaluated (but the value is lost, you didn't do anything with it) and finally the expression (< 6 7)
was evaluated and its result returned: #t
.