[英]Bind non-monadic functions to a monad
Maybe this is an often asked question, but I did not found an answer. 也许这是一个经常被问到的问题,但我没有找到答案。
The bind of a monad is defined like that: monad的绑定定义如下:
(>>=) :: m a -> (a -> m b) -> m b
At the moment I'm doing this: 目前我正在这样做:
foo :: Int
foo = sum $ ((*11) . (+2)) `map` [1..4]
I want to achieve a syntax like this, because I think it's more readable: 我想实现这样的语法,因为我认为它更具可读性:
[1..4] >>= (+2) >>= (*11) >>= sum
I don't know the right operators instead of >>=
. 我不知道正确的运算符而不是
>>=
。
Besides: foo is 198. 此外:foo是198。
The most readable in this case is certainly 在这种情况下最可读的当然是
sum [ (x+2)*11 | x<-[1..4] ]
but if you want it point-free and without extra parens, just rewrite your original line with the infix fmap operator : 但如果你想要它没有点,没有额外的parens,只需用infix fmap运算符重写原始行:
sum $ (*11) . (+2) <$> [1..4]
If you just want to turn the order around, you can replace .
如果您只想转动订单,可以更换
.
with the equivalent flipped operator from Control.Category
, and $
with its flipped version eg from lens
使用来自
Control.Category
的等效翻转运算符,以及带翻转版本的 $
, 例如来自lens
[1..4] & fmap((+2)>>>(*11)) & sum
Then again, if you're after mathematical elegance and want it to "work like a monad", this isn't possible because there's nothing monadic going on here. 再说一遍,如果你追求数学优雅并希望它“像monad一样工作”,这是不可能的,因为这里没有任何monadic。 You could however argue that
sum
is a Cokleisli arrow in the (not definable, in Haskell 98) Monoid
-limited list comonad. 然而,你可以争辩说,
sum
是一个Cokleisli箭头(不可定义,在Haskell 98中) Monoid
-limited列表comonad。 We can approximate this by the NonEmpty comonad and write 我们可以通过NonEmpty comonad来估算这个并写
extract $ fromList [1..4] =>> (extract>>>(+2)>>>(*11)) =>> sum.toList
but this is ridiculous. 但这太荒谬了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.