[Haskell-beginners] Very basic question on monads

David McBride dmcbride at neondsl.com
Wed Feb 23 13:29:54 CET 2011


You should know that the answers are at:
http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours/Answers

parseNumber'' = many1 digit >>= return . Number . read

On Wed, Feb 23, 2011 at 5:31 AM, Chaddaï Fouché
<chaddai.fouche at gmail.com> wrote:
> On Wed, Feb 23, 2011 at 6:30 AM,  <blackcat at pro-ns.net> wrote:
>> I'm working through the "Write Yourself a Scheme" wikibook and having
>> trouble with one of the exercises.  For the function parseNumber :: Parser
>> LispVal, both
>>
>> parseNumber = liftM (Number . read) $ many1 digit
>> parseNumber' = do digits <- many1 digit
>>                 return $ (Number . read) digits
>>
>> work.  But
>>
>> parseNumber'' = many1 digit >>= liftM read >>= liftM Number
>
> You misunderstand liftM : liftM takes an ordinary function (a -> b)
> and "lift" it so that it acts inside the monad and become (m a -> m b)
> thus the parameter of "liftM f" must be a monadic action but through
> (>>=) you feed it an ordinary value since (>>=) bind a monadic action
> (m a) to a function that takes an ordinary value and return an action
> (a -> m b). You used liftM as if it was (return .)
>
> The correct usage would have been :
>
>> parseNumber'' = liftM (Number . read) (many1 digit)
>
> like your parseNumber
>
> or (using Applicative if you wish to do so) :
>
>> parseNumber'' = Number . read <$> many1 digit
>
> --
> Jedaï
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



More information about the Beginners mailing list