Monad 的脱糖注释
当我学习 Haskell 时,我意识到 do
表示法只是语法糖:
a = do x <- [3..4]
[1..2]
return (x, 42)
翻译成
a = [3..4] >>= (\x -> [1..2] >>= (\_ -> return (x, 42)))
我意识到我可能会使用 do 表示法,但我想了解翻译中发生了什么。因此,纯粹出于教学原因,ghc/ghci 有没有办法为我提供用 do 表示法编写的相当复杂的 monad 的相应绑定语句?
编辑。事实证明 #haskell 上的 lambdabot 可以做到这一点:
<Guest61347> @undo do x <- [3..4] ; [1..2] ; return (x, 42)
<lambdabot> [3 .. 4] >>= \ x -> [1 .. 2] >> return (x, 42)
这是撤消插件。
As I'm learning Haskell I'm realizing that do
notation is just syntatic sugar:
a = do x <- [3..4]
[1..2]
return (x, 42)
Translates into
a = [3..4] >>= (\x -> [1..2] >>= (\_ -> return (x, 42)))
I realize that I'll probably use do-notation but I'd like to understand whats going on in translation. So purely for pedagogical reasons, is there a way for ghc/ghci to give me the corresponding bind statements for a fairly complex monad written in do-notation?
Edit. It turns out lambdabot on #haskell can do this:
<Guest61347> @undo do x <- [3..4] ; [1..2] ; return (x, 42)
<lambdabot> [3 .. 4] >>= \ x -> [1 .. 2] >> return (x, 42)
Here's the source code the Undo plugin.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以要求 GHC 脱糖器的输出,但这也会脱糖许多其他语法。
首先,我们将您的代码放入模块
Foo.hs
中:接下来,我们将要求 GHC 对其进行编译并在脱糖阶段后输出结果:
输出可能看起来相当混乱,因为它是 Haskell 的一个变体,称为 Core,用作 GHC 的中间语言。不过,一旦习惯了,阅读起来并不难。在其他一些定义的中间,我们找到了您的:
Core 不太漂亮,但是在使用 GHC 时能够读取它非常有用,因为您可以在后期阶段之后读取转储以了解 GHC 如何优化您的代码。
如果我们删除重命名器添加的
_xyz
后缀,以及类型应用@ Xyz
和对GHC.Integer.smallInteger
的调用,并再次使运算符中缀,你会得到这样的结果: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
:Next, we'll ask GHC to compile it and output the result after the desugaring phase:
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:
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 toGHC.Integer.smallInteger
, and make the operators infix again, you're left with something like this: