开发者

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

开发者 https://www.devze.com 2023-02-07 19:53 出处:网络
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 vari

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开发者_StackOverflow.List find function but this dosent seem to return a boolean.

I am using GHCi.

Thanks,


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消