可以'全部'应用于Maybe列表吗?

时间:2017-05-12 07:49:02

标签: haskell

是否可以在all列表中使用[Maybe Int]

我知道all (< 9) [2,4,6,8,10]会返回False,但这是使用只有整数的列表。

我试图完成类似的事情,除了列表看起来像这样:
[Just 3, Just 6, Nothing, Nothing, Just 7]

我希望all (<=9) [Just 3, Just 6, Nothing, Nothing, Just 7]返回True

3 个答案:

答案 0 :(得分:23)

> all (<= Just 9) [Just 3, Just 6, Nothing, Nothing, Just 7]
True

这是有效的,因为Nothing小于任何Just x

或者,可以使用catMaybes :: [Maybe a] -> [a]模块中的Data.Maybe来放弃Nothing,并删除Just包装,将列表转换为数字列表,然后可以照常处理:

> all (<= 9) $ catMaybes [Just 3, Just 6, Nothing, Nothing, Just 7]
True

另一种选择:在Maybe Int上定义自己的谓词。

let p :: Maybe Int -> Bool
    p Nothing = True
    p (Just x) = x <= 9
 in all p [Just 3, Just 6, Nothing, Nothing, Just 7]

更好:使用p定义maybeZeta suggests

另一种选择,使用列表理解和and

and [ x <= 9 | Just x <- [Just 3, Just 6, Nothing, Nothing, Just 7] ]

答案 1 :(得分:14)

chiZeta更为深奥的解决方案将使用Compose,以便all将这两个层视为包含数字的单个结构:

GHCi> import Data.Functor.Compose
GHCi> all (<=9) $ Compose [Just 3, Just 6, Nothing, Nothing, Just 7]
True

答案 2 :(得分:13)

不确定。 maybe True (< 9)。如果您有func,则maybe default func会使用给定的函数Just;如果您有default,则使用Nothing

ghci> all (maybe True (< 9))  [Just 3, Just 6, Nothing, Nothing, Just 7]
True

您可以使用它来编写allMaybe功能:

allMaybe :: (a -> Bool) -> [Maybe a] -> Bool
allMaybe p = all (maybe True p)

或者我们可以提升&#34;你的谓词是Maybe

liftP :: (a -> Bool) -> Maybe a -> Bool
liftP _ Nothing  = True
liftP p (Just x) = p x
-- or simply 
-- liftP p = maybe True p

allMaybe' p = all (liftP p)

但这只会隐藏潜在的maybe