[Haskell-beginners] Very basic question on monads

Chaddaï Fouché chaddai.fouche at gmail.com
Wed Feb 23 11:31:06 CET 2011


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ï



More information about the Beginners mailing list