是否可以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
chi*_*chi 23
> all (<= Just 9) [Just 3, Just 6, Nothing, Nothing, Just 7]
True
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为Nothing它比任何都少Just x.
或者,可以catMaybes :: [Maybe a] -> [a]从Data.Maybe模块中使用以丢弃Nothings,并删除Just包装器,将列表转换为数字列表,然后可以照常处理:
> all (<= 9) $ catMaybes [Just 3, Just 6, Nothing, Nothing, Just 7]
True
Run Code Online (Sandbox Code Playgroud)
另一种选择:定义自己的谓词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]
Run Code Online (Sandbox Code Playgroud)
更好:定义p使用maybe,正如Zeta建议的那样.
另一种选择,使用列表理解和and:
and [ x <= 9 | Just x <- [Just 3, Just 6, Nothing, Nothing, Just 7] ]
Run Code Online (Sandbox Code Playgroud)
dup*_*ode 14
比chi和Zeta使用的更深奥的解决方案将使用,Compose以便all将两个层视为包含数字的单个结构:
GHCi> import Data.Functor.Compose
GHCi> all (<=9) $ Compose [Just 3, Just 6, Nothing, Nothing, Just 7]
True
Run Code Online (Sandbox Code Playgroud)
Zet*_*eta 13
当然.maybe True (< 9).如果你有,则maybe default func使用给定的函数,func如果你有Just,default则使用Nothing:
ghci> all (maybe True (< 9)) [Just 3, Just 6, Nothing, Nothing, Just 7]
True
Run Code Online (Sandbox Code Playgroud)
您可以使用它来编写您的allMaybe函数:
allMaybe :: (a -> Bool) -> [Maybe a] -> Bool
allMaybe p = all (maybe True p)
Run Code Online (Sandbox Code Playgroud)
或者我们可以将你的谓词"解除"到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)
Run Code Online (Sandbox Code Playgroud)
但这只会隐藏潜在的东西maybe.
| 归档时间: |
|
| 查看次数: |
1283 次 |
| 最近记录: |