简体   繁体   English

Haskell:检查Int是否在Int列表中

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

I am new to Haskell, sorry if this is a basic question. 我是Haskell的新手,对不起,如果这是一个基本问题。

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. 我目前有一个Int的列表,我正在尝试创建一个函数,它接受一个变量x并返回一个布尔值,具体取决于该变量是否存在于列表中。

I have had a search and found Data.List find function but this dosent seem to return a boolean. 我有一个搜索,发现Data.List查找函数,但这个dosent似乎返回一个布尔值。

I am using GHCi. 我正在使用GHCi。

Thanks, 谢谢,

First find the type of the function you need. 首先找到您需要的功能类型。

To "Check if" means to return either True or False, a Bool. 要“检查是否”意味着返回True或False,一个Bool。

So the function takes an Int, a list of Int (aka [Int]) and returns Bool: 所以函数接受一个I​​nt,一个Int(又名[Int])列表并返回Bool:

Int -> [Int] -> Bool

Now ask hoogle . 现在问一下hoogle

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

Hoogle is a very useful tool. Hoogle是一个非常有用的工具。 You can integrate it with ghci . 您可以将它与ghci集成

If the standard elem function didn't exist, you could have been on the right track with find . 如果标准的elem函数不存在,那么你可以使用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. 我在闲暇时间尝试学习Haskell的两个月。 Professionally, I do C/C++ for several years. 从专业角度来说,我做了几年的C / C ++。 I must say, that the first month of learning Haskell was a headspin experience. 我必须说,学习Haskell的第一个月是一个令人头疼的经历。 I always try to do things on my own if the problem is simple enough rather than using existing APIs like elem . 如果问题很简单而不是像elem那样使用现有的API,我总是试着自己做事。 I'm slowly learning the FP way, and below is my solution: 我正在慢慢学习FP方式,下面是我的解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM