2010-12-12 99 views
0

我想在列表中添加偶数项目并使用我写的以下算法来实现目标。在列表中添加偶数项目

我正的错误是:

+:预计键入<数>作为第二参数,给出:#<空隙>;其他参数分别为:4

代码:

(define (mylength alist cnt) 
    (if (null? alist) 
    0 

    (if (= (modulo cnt 2) 0)(+ (car alist) (mylength (cdr alist) (+ cnt 1))))) 
    (if (= (modulo cnt 2) 1)(mylength (cdr alist) (+ cnt 1)))) 

你能请告知我 )错误 II)算法的逻辑

谢谢!

回答

2

首先,正确缩进代码:

(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 
+0

谢谢erjiang。我没有得到你说的部分,'任何不是最后一个表达式都将被运行和抛弃'。你能详细说明一下吗? – Roy 2010-12-12 04:43:14

+0

请参阅我的编辑答案 – erjiang 2010-12-13 19:52:30

0

另一个答案是完全正确的,但你的界面不是很scheme-y。这是尾部递归更常见的形式。

; Assumes given a list of numbers. Returns sum of even indices. 
(define (mylength alist) 
    (let helper ((alist alist) (acc 0)) 
    (cond 
     ((null? alist) acc) 
     ((null? (cdr alist)) (+ acc (car alist))) 
     (else (helper (cddr alist) (+ acc (car alist)))))))