首先,正确缩进代码:
(define (mylength alist cnt)
(if (null? alist) ;
0 ; this section is wasted because
(if (= (modulo cnt 2) 0) ; it's not the last expression
(+ (car alist) (mylength (cdr alist) (+ cnt 1))))) ;
(if (= (modulo cnt 2) 1) ; this if is the last expression, but
(mylength (cdr alist) (+ cnt 1)))) ; if it's false you get #<void>
你不应该有没有既真假分支if
表达式。你必须记住,这不是C,并且任何不是最后一个表达式的东西都将被运行,然后被抛弃。
合并的最后两个if语句为一个if
声明:
(define (mylength alist cnt)
(if (null? alist)
0
(if (= (modulo cnt 2) 0)
(+ (car alist) (mylength (cdr alist) (+ cnt 1)))
(mylength (cdr alist) (+ cnt 1)))))
编辑:当我写“什么,这不是最后一个表达式将运行,然后扔掉”,我的意思是:
(begin
(+ 2 2)
(+ 4 1)
(+ 1 0)
(+ 1 1)) => 2
(let ((x 5))
(add1 x)
(+ x 2)
(* x 2)) => 10
((lambda()
(if #t 3)
(if #f 0 4)
(if #t 2))) => 2
谢谢erjiang。我没有得到你说的部分,'任何不是最后一个表达式都将被运行和抛弃'。你能详细说明一下吗? – Roy 2010-12-12 04:43:14
请参阅我的编辑答案 – erjiang 2010-12-13 19:52:30