Reputation: 157
I'm trying to create a recursive function that checks to see whether or not "a" is in an array. I'm trying to take the head of the tail and compare it to "a". However, it doesn't return the correct boolean value every time because it only take the head of the tail once. how do i make this recursive?
isElement :: Eq a => a -> [a] -> Bool
isElement a [] = False
isElement a (x:xs)
| a == x = True
| otherwise = False
where x = head(xs)
Upvotes: 2
Views: 7090
Reputation: 70257
There are a couple of issues. First off, your where
block is not accomplishing anything. x
is already known to be the head of the list because it's part of the (x:xs)
construct, which destructures the list directly into the variables. So that line can be entirely removed. Second, there's no actual recursion here. You need to call isElement
in the false case to check the rest of the list, rather than simply returning False
.
isElement :: Eq a => a -> [a] -> Bool
isElement a [] = False
isElement a (x:xs)
| a == x = True
| otherwise = isElement a xs
Note that compiling your program with -Wall
will give you warnings about a lot of things, including unused variables. In particular, the fact that, in your example (after removing the where
block), xs
was an unused variable should be a red flag and, in this case, gives us some insight into the problem: you never used the rest of the list, so the rest of the list gets ignored.
Upvotes: 4