Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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,

like image 205
Joseph Avatar asked Jan 31 '11 01:01

Joseph


People also ask

How do you check if an element is in a list in Haskell?

elem :: element -> list -> Bool. Use elem if you want to check whether a given element exists within a list.

How do I find duplicates in Haskell?

if it is just about knowing if the list contains duplicates you can use the nub function in Data. List like so: hasDup l = nub l == l (nub removes all duplicates... so this will be true only if there are no duplicates in the list.)

How do you check types in Haskell?

If you are using an interactive Haskell prompt (like GHCi) you can type :t <expression> and that will give you the type of an expression. e.g. or e.g.


3 Answers

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.

like image 127
Etienne Laurin Avatar answered Oct 03 '22 20:10

Etienne Laurin


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.

like image 21
ephemient Avatar answered Oct 03 '22 22:10

ephemient


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
like image 42
eigenfield Avatar answered Oct 03 '22 20:10

eigenfield