在 Haskell 中创建唯一标签 [英] Creating unique labels in Haskell

查看:33
本文介绍了在 Haskell 中创建唯一标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Haskell 编写一个简单的命令式语言的编译器,输出 Java 字节码.我已经到了发出字节码的抽象表示的地步.

I'm writing a compiler for a simple imperative language in Haskell, outputting Java bytecode. I've gotten to the point where I'm emitting an abstract representation of bytecodes.

在编写编译 if 语句的代码时,我遇到了一些麻烦.要实现 if 语句,我需要跳转到的标签.因此,我需要为该标签生成一个名称,并且该名称必须是唯一的.

While writing code for compiling if-statements I ran in to some trouble. To implement if-statements I need labels to jump to. Therefore I need to generate a name for that label, and that name needs to be unique.

我的第一个想法是通过 compileStatement 线程化一些状态,即

My first thought was to thread some state through compileStatement, i.e

compileStatement :: Statement -> UniqueIDState -> [AbstractInstruction]

当然,compilerStatement 是递归的,所以使用这种方法需要我将唯一 ID 生成器的状态从递归调用中传递回来:

Of course, compilerStatement is recursive, so using this method would require me to pass the state of the unique ID generator back upp from the recursive calls:

compileStatement :: Statement -> UniqueIDState -> (UniqueIdState, [AbstractInstruction])

这似乎有点笨拙,尤其是当我意识到我将来需要携带更多状态时;有没有更优雅的方式?

This seems a bit clumsy, especially if I realize I need to carry around more state in the future; is there a more elegant way?

推荐答案

你需要一个独特的供应".在 Haskell 中执行此操作的常用方法是通过 State monad 线程化一个计数器,这会自动处理您描述的管道问题.

You need a "unique supply". The usual way to do this in Haskell is by threading a counter through the State monad, which automates the plumbing problem you describe.

这篇关于在 Haskell 中创建唯一标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆