Desugaring do-notation for Monads

不打扰是莪最后的温柔 提交于 2019-11-28 05:22:39

You can ask for the output of GHC's desugarer, however this will also desugar a lot of other syntax.

First, we'll put your code in a module Foo.hs:

module Foo where

a = do x <- [3..4]
       [1..2]
       return (x, 42)

Next, we'll ask GHC to compile it and output the result after the desugaring phase:

$ ghc -c Foo.hs -ddump-ds

The output may look rather messy, because it is a variant of Haskell called Core that is used as GHC's intermediate language. However, it's not too hard to read once you get used to it. In the middle of some other definitions we find yours:

Foo.a :: [(GHC.Integer.Type.Integer, GHC.Integer.Type.Integer)]
LclIdX
[]
Foo.a =
  >>=_agg
    @ GHC.Integer.Type.Integer
    @ (GHC.Integer.Type.Integer, GHC.Integer.Type.Integer)
    (enumFromTo_ag7
       (GHC.Integer.smallInteger 3) (GHC.Integer.smallInteger 4))
    (\ (x_adf :: GHC.Integer.Type.Integer) ->
       >>_agn
         @ GHC.Integer.Type.Integer
         @ (GHC.Integer.Type.Integer, GHC.Integer.Type.Integer)
         (enumFromTo_ags
            (GHC.Integer.smallInteger 1) (GHC.Integer.smallInteger 2))
         (return_aki
            @ (GHC.Integer.Type.Integer, GHC.Integer.Type.Integer)
            (x_adf, GHC.Integer.smallInteger 42)))

Core isn't too pretty, but being able to read it is very useful when working with GHC, as you can read the dump after later stages to see how GHC is optimizing your code.

If we remove the _xyz suffixes added by the renamer, as well as the type applications @ Xyz and the calls to GHC.Integer.smallInteger, and make the operators infix again, you're left with something like this:

Foo.a :: [(GHC.Integer.Type.Integer, GHC.Integer.Type.Integer)]
Foo.a = enumFromTo 3 4 >>= \x -> enumFromTo 1 2 >> return (x, 42)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!