3 ms·
Monads are used for abstracting computation composition. In any given Haskell code, I'd say at least 80% of my monadic code is non-imperative. There are imperat
by jmillikin 16y ago
Monads are used for abstracting computation composition. In any given Haskell code, I'd say at least 80% of my monadic code is non-imperative. There are imperative monads (ST, IO), but also many many functional ones. I've written an introductory article at < http://ianen.org/articles/monad-is-not-difficult/ http://ianen.org/articles/monad-is-not-difficult/ >.
The first example in the article demonstrates what I mean by "computation composition". "mdiv(2.0, 3.0)" returns a Maybe, not a float, and before using it as a float the inner value must be unpacked. That can be done without the monad operators, but is verbose and error-prone:
mdiv :: Float -> Float -> Float
mdiv a b = if b == 0
then Nothing
else Just (a / b)
with_maybe :: Maybe Float
with_maybe = case mdiv 2.0 2.0 of
Nothing -> Nothing
Just val1 -> case mdiv 3.0 0.0 of
Nothing -> Nothing
Just val2 -> case mdiv val1 val2 of
Nothing -> Nothing
Just val3 -> Just val3
Here's that same example, rewritten to use the monadic operators (with explicit lambdas, as in the article):
with_maybe :: Maybe Float
with_maybe =
mdiv 2.0 2.0 >>= (\val1 ->
mdiv 3.0 0.0 >>= (\val2 ->
mdiv val1 val2 >>= (\val3 ->
Just val3)))
And, for completeness, using Haskell's lambda-hiding 'do' notation:
with_maybe :: Maybe Float
with_maybe = do
val1 <- mdiv 2.0 2.0
val2 <- mdiv 3.0 0.0
val3 <- mdiv val1 val2
Just val3