On Sat, Sep 4, 2010 at 2:06 PM, michael rice <span dir="ltr">&lt;<a href="mailto:nowgate@yahoo.com">nowgate@yahoo.com</a>&gt;</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>--            &gt;&gt;= \str -&gt; return (read str :: Color)<br></td></tr></tbody></table></blockquote><div><br></div><div>First, you don&#39;t need the type annotation here. Haskell will infer it from the annotation on myAction. (You also don&#39;t need the type on myAction, but that&#39;s not important now.)</div>
<div><br></div><div>myAction = getLine &gt;&gt;= \str -&gt; return (read str)</div><div><br></div><div>Second, you have the pattern \x -&gt; f (g x), so you can replace the lambda with function composition.</div><div><br>
</div><div>myAction = getLine &gt;&gt;= return . read</div><div><br></div><div>Third, there is a standard function liftM, defined in Control.Monad, where liftM f m = m &gt;&gt;= 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 &lt;$&gt; 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 &lt;$&gt; getLine</td></tr></tbody></table></blockquote></div><br>-- <br>Dave Menendez &lt;<a href="mailto:dave@zednenem.com">dave@zednenem.com</a>&gt;<br>
&lt;<a href="http://www.eyrie.org/~zednenem/">http://www.eyrie.org/~zednenem/</a>&gt;<br>