Haskell: Check if Int is in a list of Int's

I am new to Haskell, sorry if this is a basic question.

I currently have a list of Int's and I am trying to create a function that takes a variable x and returns a boolean depending whether the variable exists in the list.

I have had a search and found Data.List find function but this dosent seem to return a boolean.

I am using GHCi.

Thanks,


Solution 1:

First find the type of the function you need.

To "Check if" means to return either True or False, a Bool.

So the function takes an Int, a list of Int (aka [Int]) and returns Bool:

Int -> [Int] -> Bool

Now ask hoogle.

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

Hoogle is a very useful tool. You can integrate it with ghci.

Solution 2:

If the standard elem function didn't exist, you could have been on the right track with find.

myElem :: (Eq a) => a -> [a] -> Bool
myElem x = maybe False (const True) . find (== x)

There's lots of other ways to implement it too, like

myElem x = any (== x)
myElem x = or . map (== x)
myElem x = not . null . filter (== x)
myElem x = foldr (\y b -> y == x || b) False

etc.

Solution 3:

I'm in my 2 months of trying to learn Haskell during my spare time. Professionally, I do C/C++ for several years. I must say, that the first month of learning Haskell was a headspin experience. I always try to do things on my own if the problem is simple enough rather than using existing APIs like elem. I'm slowly learning the FP way, and below is my solution:

isMember n [] = False
isMember n (x:xs)
    | n == x = True
    | otherwise = isMember n xs

Usage:

isMember 2 [1,9,4,5] -- False
isMember 2 [4,5,2,9] -- True