Ethan Lim
Ethan Lim

Reputation: 93

I'm trying to create my own (elem) function

myElement [] = []
myElement [h] = [h]
myElement (h:t)
| h == myElement t  = True
| otherwise         = False

Hi guys, I'm struggling creating my own elem function, because I'm not allowed to use any predefined function in haskell for homework. I bet my code is not actually working but I can't think other way else.

Upvotes: 0

Views: 123

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477055

The main problem is that your function only works with one parameter, whereas elem will take two parameters: the needle (we are looking for), and the haystack.

This thus means that myElem has as type:

myElem :: Eq a => a -> [a] -> Bool

another problem is that myElem [h] = [h] makes not much sense, if you have a list with one element, you should not return that element, but you should, just like every clause, return a Bool.

As for the last clause, if h is not the element we are looking for, we need to use recursion to look for the remaining haystack.

The function thus looks like:

myElem :: Eq a => a -> [a] -> Bool
myElem x = go
    where go [] = … a Bool …
          go (h:t)
              | x == h = …
              | otherwise = … recursive call …

where you need to fill in the parts.

Upvotes: 4

Related Questions