use*_*101 16 haskell if-statement combinators maybe
Haskell代码中经常出现以下模式.是否有更短的方式来写它?
if pred x
then Just x
else Nothing
Run Code Online (Sandbox Code Playgroud)
Lan*_*dei 28
您正在寻找mfilter
的Control.Monad
:
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
-- mfilter odd (Just 1) == Just 1
-- mfilter odd (Just 2) == Nothing
Run Code Online (Sandbox Code Playgroud)
请注意,如果条件不依赖于内容MonadPlus
,您可以改为:
"foo" <$ guard (odd 3) -- Just "foo"
"foo" <$ guard (odd 4) -- Nothing
Run Code Online (Sandbox Code Playgroud)
嗯...你正在寻找一个带有a
一个函数a -> Bool
并返回一个的组合子Maybe a
.停止!霍格时间.没有完全匹配,但find
非常接近:
find :: (a -> Bool) -> [a] -> Maybe a
Run Code Online (Sandbox Code Playgroud)
我怀疑你能在某个地方找到你的功能.但为什么不自己定义呢?
ifMaybe :: (a -> Bool) -> a -> Maybe a
ifMaybe f a | f a = Just a
ifMaybe _ _ = Nothing
Run Code Online (Sandbox Code Playgroud)
使用:
(?:) (5>2) (Just 5,Nothing)
Run Code Online (Sandbox Code Playgroud)
来自Data.Bool.HT.
您可以使用它guard
来实现此行为:
guard (pred x) >> return x
Run Code Online (Sandbox Code Playgroud)
这是一个非常有用的行为,我甚至ensure
在我自己的一小段代码中定义了一次性(每个人都有这样的东西,对吧?;-):
ensure p x = guard (p x) >> return x
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
922 次 |
最近记录: |