gpt4 book ai didi

haskell - 将非 monadic 函数绑定(bind)到 monad

转载 作者:行者123 更新时间:2023-12-01 03:43:43 24 4
gpt4 key购买 nike

也许这是一个经常被问到的问题,但我没有找到答案。

monad 的绑定(bind)定义如下:

(>>=)  :: m a -> (a -> m b) -> m b

目前我正在这样做:

foo :: Int
foo = sum $ ((*11) . (+2)) `map` [1..4]

我想实现这样的语法,因为我认为它更具可读性:

[1..4] >>= (+2) >>= (*11) >>= sum

我不知道正确的运算符而不是 >>=

此外:foo 是 198。

最佳答案

在这种情况下,最可读的当然是

   sum [ (x+2)*11 | x<-[1..4] ]

但是如果你想要它没有点并且没有额外的括号,只需用 infix fmap operator 重写你的原始行:

   sum $ (*11) . (+2) <$> [1..4]

如果您只想调转顺序,可以将 . 替换为等效的翻转运算符 from Control.Category , 和 $its flipped version e.g. from lens

   [1..4] & fmap((+2)>>>(*11)) & sum

话又说回来,如果您追求数学上的优雅并希望它“像 monad 一样工作”,这是不可能的,因为这里没有 monadic。但是,您可以争辩说 sum 是(不可定义,在 Haskell 98 中)Monoid-limited list comonad 中的 Cokleisli 箭头。我们可以用 NonEmpty comonad 来近似这个并写

    extract $ fromList [1..4] =>> (extract>>>(+2)>>>(*11)) =>> sum.toList

但这太 absurd 了。

关于haskell - 将非 monadic 函数绑定(bind)到 monad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25283012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com