In Scheme you need to use (let () ...) in both if and cond to introduce local definitions. That is
(cond [(even? x) (define y 42) (+ x y)] [else 'huh]) will not work in Scheme, neither will (cond [(even? x) (begin (define y 42) (+ x y))] [else 'huh]). To introduce a new scope (let () ...) is needed. (cond [(even? x) (let () (define y 42) (+ x y))] [else 'huh]) will. In Racket the principle is that, if there is "room", then you define works. This implies that that (cond [(even? x) (define y 42) (+ x y)] [else 'huh]) works. Note that begin is not needed. 2014-03-16 22:06 GMT+01:00 Justin Zamora <jus...@zamora.com>: > Ok, but why is "cond" defined to behave differently? I expected "cond" to > behave the same as "if". > > Justin > > On Mar 16, 2014 4:59 PM, "Jens Axel Søgaard" <jensa...@soegaard.net> wrote: >> >> The problem is that begin does not introduce a new scope. >> You can use (let () ...) or block instead. >> >> >> http://docs.racket-lang.org/reference/block.html?q=block#%28form._%28%28lib._racket%2Fblock..rkt%29._block%29%29 >> >> /soegaard >> >> >> 2014-03-16 21:38 GMT+01:00 Justin Zamora <jus...@zamora.com>: >> > What is the reason for not allowing internal definitions in the "then" >> > and >> > "else" parts of an "if"? >> > >> > This fails with "define: not allowed in an expression context": >> > (if (< 3 4) >> > 5 >> > (begin >> > (define a 7) >> > a)) >> > >> > But the equivalent "cond" works fine: >> > (cond >> > [(< 3 4) 5] >> > [else (define a 7) >> > a]) >> > >> > I notice that the expansion of "cond" encloses the clauses inside >> > (let-values () ...). Why doesn't "if" allow this? >> > >> > Justin >> > >> > ____________________ >> > Racket Users list: >> > http://lists.racket-lang.org/users >> > >> >> >> >> -- >> -- >> Jens Axel Søgaard -- -- Jens Axel Søgaard ____________________ Racket Users list: http://lists.racket-lang.org/users