简体   繁体   中英

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

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 <- ay <- 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM