haskell – 寻找`if p x then x else empty`结构的概括

栏目: 编程语言 · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/34089511/looking-for-generalisation-of-the-if-p-x-then-x-else-empty-construct

我有几个片段,他们觉得他们正在做同样的事情,但我并不完全相信有一个通用的构造来处理它们.在一个地方,我有

ensure :: (String -> Bool) -> String -> String
ensure p x =
    if p x then
        x
    else
        ""

这可能在使用中看起来像

ensure (/= "kim") "alex"    -- returns "alex"
ensure (/= "kim") "kim"     -- returns ""

在另一个,我有非常相似

ensure :: (a -> Bool) -> Maybe a -> Maybe a
ensure p maybeX = do
    x <- maybeX
    if p x then
        Just x
    else
        Nothing

相反,这看起来像

ensure even 6     -- returns Just 6
ensure even 11    -- returns Nothing

两者都根据某个谓词检查值是否正确,如果不是,则返回默认的“空”值.虽然有一点点差别 – 这意味着第二个功能可以重写为

ensure :: (Maybe a -> Bool) -> Maybe a -> Maybe a
ensure p maybeX =
    if p x then
        x
    else
        Nothing

使它们更相似,将“解开”Maybe的责任放在谓词上.有了这个新的定义,这两个功能都属于

ensure :: Alternative f => (f a -> Bool) -> f a -> f a
ensure p x =
    bool x empty (p x)

所以,我的问题是,

这个bool x empty(p x)是否以某种形式存在,所以我不必自己实现这个功能?内联bool x empty(p x)的问题在于,在我的情况下,p和x都很长.

有两个建议.一个使用Monoid:

ensure :: Monoid a => (a -> Bool) -> a -> a
ensure p a = if p a then a else mempty

另一个使用MonadPlus:

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

翻译自:https://stackoverflow.com/questions/34089511/looking-for-generalisation-of-the-if-p-x-then-x-else-empty-construct


以上所述就是小编给大家介绍的《haskell – 寻找`if p x then x else empty`结构的概括》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro Django

Pro Django

Marty Alchin / Apress / 2008-11-24 / USD 49.99

Django is the leading Python web application development framework. Learn how to leverage the Django web framework to its full potential in this advanced tutorial and reference. Endorsed by Django, Pr......一起来看看 《Pro Django》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具