[Haskell-cafe] Making monadic code more concise
Alexander Solla
ajs at 2piix.com
Mon Nov 15 13:17:13 EST 2010
On Nov 15, 2010, at 9:43 AM, Ling Yang wrote:
> Specifically: There are some DSLs that can be largely expressed as
> monads,
> that inherently play nicely with expressions on non-monadic values.
This, to me, is a big hint that applicative functors could be useful.
Every monad is an applicative functor. Given a monad instance for F,
you can do:
instance Applicative F where
pure = return
(<*>) = ap
<$> is an alias of fmap. <*> can be interpreted as a kind of
"lifting" product operator (Examine the types as you learn it. The
notation will become transparent once you "get it"). So you write
expressions like:
data F a = F a -- We'll assume F is instantiated as a monad
data Foo = Foo Int Int Int
foo :: F Foo
foo = Foo <$> monad_action_that_returns_an_int_for_your_first_argument
<*> monad_action_that_returns_an_int_for_your_second_argument
<*> monad_action_that_etc
Your test
test = liftM2 (+) (coin 0.5) (coin 0.5)
translates to:
test = (+) <$> (coin 0.5)
<*> (coin 0.5)
You can't really express a test in 5 arguments (I think there's no
liftM5...) but it's easy with <$> and <*>:
test = Five <$> one
<*> two
<*> three
<*> four
<*> five
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20101115/05f47a35/attachment.html
More information about the Haskell-Cafe
mailing list