Reputation: 677
problem takes a list e.g L = (4 11 16 22 75 34) and gets tested for a condition (modulus 2) then returns a list with all the items in the list that pass the test e.g newL = (4 16 34)
Here is the code:
(define clean-list
(lambda (x)
(list x (test x))))
(define test
(lambda (x)
(cond (= 0 (modulo (car x) 2))
(cons (car x) (test(cdr x)))
(else (test(cdr x))))
))
output:
((4 11 16 22 75 34) 0)
I debugged the code, it foes into (modulo (car x) 2) then returns to clean-list and exits, all after first run, please explain that and why it returns a 0 at the end of list. Also any feedback or improvement in code would be appreciated.
Upvotes: 0
Views: 701
Reputation: 206567
Here's a tail-recursive version of the function.
(define test
(lambda (x)
(define (helper in out)
(if (null? in)
out
(if (= 0 (modulo (car in) 2))
(helper (cdr in) (append out (list (car in))))
(helper (cdr in) out))))
(helper x '())
))
(define clean-list
(lambda (x)
(list x (test x))))
(write (clean-list '(4 11 16 22 75 34)))
The output:
((4 11 16 22 75 34) (4 16 22 34))
PS. When I tested the code at repl.it, I had to change modulo
to mod
.
Upvotes: 0
Reputation: 780798
You're missing a set of parentheses. You're also missing a test for the recursion bottoming out.
(define test
(lambda (x)
(cond ((eq? x '()) '())
((= 0 (modulo (car x) 2))
(cons (car x) (test(cdr x))))
(else (test(cdr x))))
))
The general syntax of cond
is:
(cond (<test1> <result1>)
(<test2> <result2>)
...)
In your code <test1>
was simply =
, not (= 0 (modulo (car x) 2))
.
Upvotes: 3