Reputation: 331
I am trying to add an element into a list if it is zero as part of a recursive function that removes all non-zeroes from a list. if it is non-zero then I just want the code to continue on. Here's what I have so far:
(cons
(cond [(zero? (first list_of_numbers))
(first list_of_numbers)])
(continue the recursive function))
However, I get the following error:
cond: all question results were false
Upvotes: 1
Views: 86
Reputation: 7568
You're asked to write a recursive function, so you should start with the terminating condition/ base case:
(define (keep-zeros lst)
(cond ((empty? lst) '())
In the next cond
branch, you will use your condition (zero?
) and if (first lst)
passes, you will cons
it to the result of (keep-zeros (rest lst))
:
((zero? (first lst))
(cons (first lst)
(keep-zeros (rest lst))))
Final cond
branch- if that number is non-zero, you will just drop it and call your function on the rest of list:
(else (keep-zeros (rest lst)))))
All together:
(define (keep-zeros lst)
(cond ((empty? lst) '())
((zero? (first lst))
(cons (first lst)
(keep-zeros (rest lst))))
(else (keep-zeros (rest lst)))))
Test:
> (keep-zeros (cons 0 (cons 3 (cons 4 (cons 0 empty)))))
(cons 0 (cons 0 '()))
Upvotes: 2