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,
elem :: element -> list -> Bool. Use elem if you want to check whether a given element exists within a list.
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.)
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With