Reputation: 5971
How do I write this function using the >>= operator?
parseNumber2 :: Parser LispVal
parseNumber2 = do x <- many1 digit
return $ (Number . read) x
Upvotes: 3
Views: 397
Reputation: 139930
A straightforward desugaring of the do-notation gives
parseNumber2 :: Parser LispVal
parseNumber2 = many1 digit >>= (return . Number . read)
but the more idiomatic way is to use fmap
or the equivalent <$>
operator from Control.Applicative
parseNumber2 = Number . read <$> many1 digit
To desugar do-notation:
Flip any <-
bindings over to the right side and add >>=
and a lambda abstraction
do x <- a
y <- b
...
becomes
a >>= \x ->
b >>= \y ->
...
For any non-binding forms, add a >>
on the right:
do a
b
...
becomes
a >>
b >>
...
Leave the last expression alone.
do a
becomes
a
Applying these rules to your code, we get
parseNumber2 =
many1 digit >>= \x ->
return $ (Number . read) x
Do some simplifications
parseNumber2 = many1 digit >>= \x -> (return . Number . read) x
parsenumber2 = many1 digit >>= (return . Number . read)
Now, for any monad, fmap
or <$>
can be defined as
f <$> x = x >>= (return . f)
Use this to get the idiomatic form
parseNumber2 = Number . read <$> many1 digit
Upvotes: 13