Reputation: 19
I'm trying to see if a certain element is in a list, for example (in-list? '+ '(- + / *))
would return #t
, while (in-list? '> '(- + / *))
would return #f
.
So far I have this for my code:
(define in-list?
(lambda (s lst)
(if (eq? s (first lst))
#t
(in-list? s (rest lst)))))
When I check using (in-list? '+ '(- + / *))
, it returns true, but using the other example I get an error message that says:
first: contract violation
expected: (and/c list? (not/c empty?))
given: '()
I'm confused on why this error is happening and was wondering if someone could help me understand. Thanks!
Upvotes: 1
Views: 875
Reputation: 57446
You're missing a base case to check if the list is empty. Here's a minimal repro, calling first
on an empty list
> (first '())
. . first: contract violation
expected: (and/c list? (not/c empty?))
given: '()
You can use empty?
to check if the list is empty as the first condition branch and return false instead of calling first
on an empty list:
(define in-list?
(lambda (s lst)
(cond
[(empty? lst) #f]
[(eq? s (first lst)) #t]
[else (in-list? s (rest lst))])))
Upvotes: 3