Search code examples
haskellapplicativedo-notation

de sugaring do notation


I want to de sugar the following do notation. But im unsure whether I have got it right:

Is:

quote   = do
    time        <- qtime
    qcomma
    ask         <- double
    qcomma
    bid         <- double
    qcomma
    askVolume   <- double
    qcomma
    bidVolume   <- double
    endOfLine
    return $ Quote time ask bid askVolume bidVolume

And

quote   = Quote <$> (qtime <* qcomma)
                <*> (double <* qcomma)
                <*> (double <* qcomma)
                <*> (double <* qcomma)
                <*> (double <* endOfLine)

Equivalent to:

qtime >>= (\time -> qcomma) 
    >> double 
        >>= (\ ask -> qcomma)  
            >> double  
                >>= (\bid -> qcomma) 
                    >> double
                        >>= (\askVolume  -> qcomma) 
                            >> double
                                >>= (\bidVolume  -> endOfLine)
                                    return (Quote time ask bid askVolume bidVolume ) 

Any help is appreciated!


Solution

  • The do notation desugars to nested lambdas, because (for example) time is in scope for the rest of the do block, not just the first call to qcomma:

    qtime >>= (
      \time -> qcomma
          >> double 
          >>= (\ ask -> qcomma
                   >> double  
                   >>= (\bid -> qcomma 
                           >> double
                           >>= (\askVolume  -> qcomma 
                                        >> double
                                        >>= (\bidVolume  -> endOfLine
                                              return (Quote time ask bid askVolume bidVolume ))))))
    

    The applicative version might have the same effect, but is not desugared to anything.

    Starting with GHC 8, the do notation might desugar to applicative code if (ApplicativeDo is turned on and) the compiler can determine that >>= isn't necessary and the more general Applicative instance has the same meaning.