On Sat, Sep 4, 2010 at 2:06 PM, michael rice <span dir="ltr"><<a href="mailto:nowgate@yahoo.com">nowgate@yahoo.com</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<table cellspacing="0" cellpadding="0" border="0"><tbody><tr><td valign="top" style="font:inherit">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?<br>
<br>Michael<br><br><br>import Control.Applicative<br><br>data Color<br> = Red<br> | Blue<br> | Green<br> | Yellow<br> | Orange<br> | Brown<br> | Black<br> | White<br> deriving (Show, Read, Eq, Enum, Ord, Bounded)<br>
<br>-- myAction :: IO Color<br>-- myAction = getLine<br>-- >>= \str -> return (read str :: Color)<br></td></tr></tbody></table></blockquote><div><br></div><div>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.)</div>
<div><br></div><div>myAction = getLine >>= \str -> return (read str)</div><div><br></div><div>Second, you have the pattern \x -> f (g x), so you can replace the lambda with function composition.</div><div><br>
</div><div>myAction = getLine >>= return . read</div><div><br></div><div>Third, there is a standard function liftM, defined in Control.Monad, where liftM f m = m >>= return . f, so</div><div><br></div><div>myAction = liftM read getLine</div>
<div><br></div><div>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</div><div></div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<table cellspacing="0" cellpadding="0" border="0"><tbody><tr><td valign="top" style="font:inherit">myAction :: IO Color<br>myAction = read <$> getLine</td></tr></tbody></table></blockquote></div><br>-- <br>Dave Menendez <<a href="mailto:dave@zednenem.com">dave@zednenem.com</a>><br>
<<a href="http://www.eyrie.org/~zednenem/">http://www.eyrie.org/~zednenem/</a>><br>