cond 在 Scheme 中是如何工作的?

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

为什么它总是 return 的值为 (- n 1)?为什么它不执行 (list-ref (cdr items) (- n 1)) ?

您在最后一个子句中忘记了 else

相反,它使用 list-ref 作为条件(它始终是真实的,因为所有过程都是真实的),并评估您的其他两个子表单并返回最后一个。