Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i write the following function with the >>= operator

Tags:

haskell

monads

How do I write this function using the >>= operator?

parseNumber2 :: Parser LispVal
parseNumber2 = do x <- many1 digit
                  return $ (Number . read) x
like image 248
Luke Avatar asked Mar 02 '26 04:03

Luke


1 Answers

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:

  1. Flip any <- bindings over to the right side and add >>= and a lambda abstraction

    do x <- a
       y <- b
       ...
    

    becomes

    a >>= \x ->
    b >>= \y ->
    ...
    
  2. For any non-binding forms, add a >> on the right:

    do a
       b
       ...
    

    becomes

    a >>
    b >>
    ...
    
  3. 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
like image 140
hammar Avatar answered Mar 04 '26 17:03

hammar