Reputation: 81
I am doing a practice question where it asks to define a function that is supposed to produce all elements in a list, loi, that can be divided by 3 or a natural number, mult, but not both.
Below is my code:
(define (keep-multiples-of-three-or loi mult)
(cond
[(empty? loi) empty]
[else (cond [(empty? loi) empty]
[(and (not (equal? 3 mult))
(or (equal? (remainder (first loi) 3) 0)
(equal? (remainder (first loi) mult) 0)))
(first loi)]
[else (keep-multiples-of-three-or (rest-loi)
mult)]))]))
for (keep-multiples-of-three-or (cons 9 (cons 3 empty)) 3)
the error message says: cons expects 2 arguments but found only 1
.
I don’t know what is wrong here. Can somebody help me?
Upvotes: 1
Views: 1865
Reputation: 236004
You have a couple of errors:
cond
expression[(empty? loi) empty]
case is repeated two times(rest-loi)
, it's (rest loi)
cons
the result and call the recursion again(not (equal? 3 mult))
condition is making your example return an empty list, think about it: you're saying that mult
is 3
, but then you check it mult
is not 3
This should fix the issues:
(define (keep-multiples-of-three-or loi mult)
(cond [(empty? loi) empty]
[(or (equal? (remainder (first loi) 3) 0)
(equal? (remainder (first loi) mult) 0))
(cons (first loi)
(keep-multiples-of-three-or (rest loi) mult))]
[else (keep-multiples-of-three-or (rest loi) mult)]))
For example:
(keep-multiples-of-three-or (list 9 3) 3)
=> '(9 3)
(keep-multiples-of-three-or (list 1 3 5 9) 5)
=> '(3 5 9)
Upvotes: 1