2

Maybe this is an often asked question, but I did not found an answer.

The bind of a monad is defined like that:

(>>=) :: 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.

asked Aug 13, 2014 at 9:45

1 Answer 1

9

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:

 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 e.g. from 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. You could however argue that sum is a Cokleisli arrow in the (not definable, in Haskell 98) Monoid-limited list comonad. We can approximate this by the NonEmpty comonad and write

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

but this is ridiculous.

answered Aug 13, 2014 at 9:54
Sign up to request clarification or add additional context in comments.

4 Comments

When in doubt simply use Cokleisli arrow in the Monoid-limited list comonad. :-)
What is a monoid-limited list?
@J.Abrahamson: not monoid-limited list, monoid-limited comonad (i.e. class MonComonad w where monExtract :: Monoid a => w a -> a), of which [] is an instance.
Ah! I see. I'd just not heard that term before.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.