On Sat, Sep 4, 2010 at 2:06 PM, michael rice <nowg...@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 <d...@zednenem.com> <http://www.eyrie.org/~zednenem/>
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe