
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) myAction :: IO Color myAction = read <$> getLine

On Sat, Sep 4, 2010 at 2:06 PM, michael rice
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

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
participants (2)
-
David Menendez
-
michael rice