[Haskell-cafe] On to applicative

michael rice nowgate at yahoo.com
Sat Sep 4 15:19:59 EDT 2010


Hi Dave,

I wrote the first one sometime last year and it seemed a suitably simple example for applicative-izing to cement the ideas in some of the code I've been going though in "Learn You a Haskell ..." Interesting stuff.

Onward and upward.

Thanks,

Michael

--- On Sat, 9/4/10, David Menendez <dave at zednenem.com> wrote:

From: David Menendez <dave at zednenem.com>
Subject: Re: [Haskell-cafe] On to applicative
To: "michael rice" <nowgate at yahoo.com>
Cc: haskell-cafe at haskell.org
Date: Saturday, September 4, 2010, 2:23 PM

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/df1a83be/attachment.html


More information about the Haskell-Cafe mailing list