编写此代码的更短的方法 [英] Shorter way to write this code
本文介绍了编写此代码的更短的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下模式在Haskell代码中非常频繁地出现。
if pred x
然后就是x
else Nothing
解决方案
您正在寻找 mfilter
在 Control.Monad
中:
mfilter :: MonadPlus m => (a - > Bool) - > m a - > ma
$注意,如果条件不依赖于
- mfilter odd(Just 1)==只有1
- mfilter odd(只是2)==没有
MonadPlus
的内容,你可以写成:
/ p>
foo< $ guard(odd 3) - 只是foo
foo< $后卫(奇数4) - 没有
The following pattern appears very frequently in Haskell code. Is there a shorter way to write it?
if pred x then Just x else Nothing
解决方案You're looking for
mfilter
inControl.Monad
:mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- mfilter odd (Just 1) == Just 1 -- mfilter odd (Just 2) == Nothing
Note that if the condition doesn't depend on the content of the
MonadPlus
, you can write instead:"foo" <$ guard (odd 3) -- Just "foo" "foo" <$ guard (odd 4) -- Nothing
这篇关于编写此代码的更短的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文