Luke
Luke

Reputation: 5971

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

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

Answers (1)

hammar
hammar

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:

  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

Upvotes: 13

Related Questions