本文介绍了使用谓词提升到Maybe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找类似于
可疑的可疑拼写是 \ p - > (< $)*>守卫。 p 。
I'm searching for something like
liftPredMaybe :: (a -> Bool) -> a -> Maybe a liftPredMaybe p a | p a = Just a | otherwise = NothingIs there such a function in Haskell already?
解决方案Not quite a ready-made solution, but with guard (from Control.Monad) and (<$) (from Data.Functor) we can write:
ensure :: Alternative f => (a -> Bool) -> a -> f a ensure p a = a <$ guard (p a)(Thanks to Daniel Wagner for suggesting a nice name for this function.)
A more pointfree spelling of dubious taste is \p -> (<$) <*> guard . p.
这篇关于使用谓词提升到Maybe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!