Reputation: 2047
All of the following are correct. But versoin 2 seems a bit confusing as it suggests an order/sequence of execution, which I think is discouraged in functional progrmaming. So I wonder what is the intuition/benifit of allowing version 2. Is it just for simpler code than versoin 3?
; version 1
(define (foo x)
(cond ((> x 0) 1)))
; version 2
(define (foo x)
(cond ((> x 0) 1 2 3)))
; version 3
(define (foo x)
(cond ((> x 0)
(begin 1 2 3))))
Upvotes: 0
Views: 143
Reputation: 58578
Scheme isn't a functional language, let alone a non-strictly evaluated one. Scheme directly provides sequenced evaluation of forms. The cond
form itself isn't strictly functional: it evaluates the test clauses in strict order, and when it finds one which yields true, it skips the remaining ones. So even without using multiple forms in a single cond
clause, we can express imperative programming:
(cond
((> x 10)
(set! y 3))
((< x 0)
(set! z 5)))
The cond
form has a long history in Lisp. It was present in some of the earliest versions of Lisp and is described in the 1960 Lisp 1 manual. In that manual, the cond
which is described in fact doesn't allow multiple forms: it arguments are strict pairs. It is still that way in the Lisp 1.5 manual. At some point, Lisp dialects started exhibiting the multiple-forms support in cond
clauses. Curiously, though, the "cond pair" terminology refuses to die.
The intuition behind allowing (cond (test1 e1 e2 .. en))
is that if you do not provide this, the programmer will get the desired behavior anyway, at the cost of extra verbiage, as your example shows with the explicit begin
: another level of parenthesis nesting accompanied by an operator symbol.
It is a backward-compatible extension to the original cond
. Allowing the extra forms doesn't change the meaning of cond
expressions that were previously correct; it adds meaning to cond
expressions that were previously ill-formed.
Other dialects of Lisp, such as Common Lisp and Emacs Lisp, have multiple form evaluation in their cond
clauses, so not allowing it in Scheme would only reduce compatibility, adding to someone's workload when they convert code from another dialect to Scheme.
Upvotes: 1
Reputation: 49803
It is not only discouraged, but pointless, for functional programming (either of version 2 or 3). But it is useful if you need to produce side-effects (for example, printing), and version 2 is a bit simpler than version 3.
Upvotes: 2