Anatoly
Anatoly

Reputation: 1916

How cond works in Scheme?

(define (list-ref items n)
  (cond ((null? items) "Out of range exception")
        ((= n 0) (car items))
        (list-ref (cdr items) (- n 1))))

(list-ref (list 1 2 3) 6)
5

Why it always return value of (- n 1)? Why it doesn't execute (list-ref (cdr items) (- n 1)) ?

Upvotes: 0

Views: 86

Answers (1)

C. K. Young
C. K. Young

Reputation: 222973

You forgot an else in the final clause.

Instead, it used list-ref as the condition (which is always truthy, since all procedures are truthy), and evaluated your other two subforms and returned the last one.

Upvotes: 1

Related Questions