Minh Triet
Minh Triet

Reputation: 1250

Omitting parentheses in cond leads to strange result

Consider the following snippet

(define (f a b c)    
   (
     cond ((and (< b c) (< b a)) (+ c  a))
          ((and (< a c) (< a b)) (+ c b))
          ((and (< c b) (< c a)) (+ b  a))
   ) 
)

(display (f 2 1 3)) ; 5
(newline)
(display (f 2 8 3)) ; 11
(newline)
(display (f 2 8 -3)) ; 10

Now if I comment the second line and second line from bottom

(define (f a b c)    
   ;(
     cond ((and (< b c) (< b a)) (+ c  a))
          ((and (< a c) (< a b)) (+ c b))
          ((and (< c b) (< c a)) (+ b  a))
   ;) 
)

The result is

#<undef>
11
10

I could not explain why omitting the parentheses lead to that result. In the second case, I expected thtat the complier would treat cond ((and (< b c) (< b a)) (+ c a)), ((and (< a c) (< a b)) (+ c b)) and ((and (< a c) (< a b)) (+ c b)) as three expressions, the latter two invalid, instead it seems they got executed.

Upvotes: 0

Views: 49

Answers (1)

alinsoar
alinsoar

Reputation: 15793

Normally cond keyword should raise an exception when it's interpreted.

But, if your interpreter does not throw any error, you are in the case of block statement, in which the evaluation of the last expression provides the result, the other ones are computed only for side-effects. The code reduces to this:

(define (f a b c)  ((and (< c b) (< c a)) (+ b  a))))

Upvotes: 1

Related Questions