[Haskell-cafe] On to applicative

David Menendez dave at zednenem.com
Sat Sep 4 14:23:27 EDT 2010


On Sat, Sep 4, 2010 at 2:06 PM, michael rice <nowgate at yahoo.com> wrote:

> The two myAction functions below seem to be equivalent and, for this small
> case, show an interesting economy of code, but being far from a Haskell
> expert, I have to ask, is the first function as small (code wise) as it
> could be?
>
> Michael
>
>
> import Control.Applicative
>
> data Color
>     = Red
>     | Blue
>     | Green
>     | Yellow
>     | Orange
>     | Brown
>     | Black
>     | White
>     deriving (Show, Read, Eq, Enum, Ord, Bounded)
>
> -- myAction :: IO Color
> -- myAction = getLine
> --            >>= \str -> return (read str :: Color)
>

First, you don't need the type annotation here. Haskell will infer it from
the annotation on myAction. (You also don't need the type on myAction, but
that's not important now.)

myAction = getLine >>= \str -> return (read str)

Second, you have the pattern \x -> f (g x), so you can replace the lambda
with function composition.

myAction = getLine >>= return . read

Third, there is a standard function liftM, defined in Control.Monad,
where liftM f m = m >>= return . f, so

myAction = liftM read getLine

Finally, we expect an instance of Monad to also be an instance of Functor,
with fmap = liftM, and we also have f <$> m = fmap f m, so


> myAction :: IO Color
> myAction = read <$> getLine


-- 
Dave Menendez <dave at zednenem.com>
<http://www.eyrie.org/~zednenem/>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20100904/bc246d04/attachment.html


More information about the Haskell-Cafe mailing list