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

Haskell

Haskell Problem Overview


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,

Haskell Solutions


Solution 1 - Haskell

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 - Haskell

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 - Haskell

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

Solution 4 - Haskell

i did it more simply like this.

l=[1,2,3,4,5]


checkIfElem :: Int -> [Int] ->Bool
checkIfElem x l 
         |x`elem` l =True
         |otherwise=False

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJosephView Question on Stackoverflow
Solution 1 - HaskellEtienne LaurinView Answer on Stackoverflow
Solution 2 - HaskellephemientView Answer on Stackoverflow
Solution 3 - HaskelleigenfieldView Answer on Stackoverflow
Solution 4 - HaskellFandamanView Answer on Stackoverflow