简体   繁体   English

使用谓词提升到Maybe

[英]Lift to Maybe using a predicate

I'm searching for something like 我正在寻找类似的东西

liftPredMaybe :: (a -> Bool) -> a -> Maybe a
liftPredMaybe p a
  | p a = Just a
  | otherwise = Nothing

Is there such a function in Haskell already? Haskell中是否有这样的功能?

Not quite a ready-made solution, but with guard (from Control.Monad ) and (<$) (from Data.Functor ) we can write: 不是现成的解决方案,但是使用guard (来自Control.Monad )和(<$) (来自Data.Functor )我们可以写:

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.) (感谢Daniel Wagner建议这个功能的好名字。)

A more pointfree spelling of dubious taste is \\p -> (<$) <*> guard . p 一个更令人讨厌的可疑口味的拼写是\\p -> (<$) <*> guard . p \\p -> (<$) <*> guard . p . \\p -> (<$) <*> guard . p

One way to compose it is like this, using Control.Monad : 使用Control.Monad构建它的一种方法是这样的:

liftPredM :: MonadPlus m => (a -> Bool) -> a -> m a
liftPredM p = mfilter p . return

Another alternative is to use Data.Foldable : 另一种方法是使用Data.Foldable

liftPredF :: (a -> Bool) -> a -> Maybe a
liftPredF f = find f . pure

This is, however, less general, so I'd lean towards favouring the MonadPlus -based implementation. 然而,这不太通用,所以我倾向于支持基于MonadPlus的实现。

In both cases, though, the idea is to first lift a 'naked' value into a container using either pure or return , and then apply a filter. 但是,在这两种情况下,我们的想法是首先使用purereturn将“裸”值提升到容器中,然后应用过滤器。 Often, you don't need to declare an actual function for this; 通常,您不需要为此声明实际功能; instead, you can just inline the composition where you need it. 相反,您可以将构图内联到您需要的位置。

Examples: 例子:

Prelude Control.Monad> liftPredMaybe even 42 :: Maybe Integer
Just 42
Prelude Control.Monad> liftPredMaybe (even . length) "foo" :: Maybe String
Nothing
Prelude Control.Monad> liftPredMaybe (odd . length) "foo" :: Maybe String
Just "foo"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM