Add even items in list
I'd like to add the even items in a list and have the following algorithm I wrote to achieve the objective.
The error I am getting is:
+: expects type <number> as 2nd argument, given: #<void>; other arguments were: 4
The code:
(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))))
Could you please advise on the i) error ii) logic of the al开发者_开发知识库gorithm
Thanks!
First, indent your code properly:
(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>
You shouldn't have if
expressions that don't have both the true and false branches. You have to remember that this isn't C, and anything that's not the last expression will be run and then thrown away.
Combine the last two if statements into one if
statement:
(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)))))
Edit: When I wrote "anything that's not the last expression will be run and then thrown away", I meant:
(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
The other answer is completely right, but your interface is not very scheme-y. This is a more common form with tail recursion.
; 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)))))))
精彩评论