Creating unique labels in Haskell

纵饮孤独 提交于 2019-11-27 16:44:42

问题


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.

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.

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

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

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?


回答1:


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.




回答2:


As was said you can use the State Monad. Or you can use "Unique Supply Monad".

http://www.haskell.org/ghc//docs/6.10.3/html/libraries/ghc/UniqSupply.html#3

It is just a wrapper around a State Moand :

http://en.wikibooks.org/wiki/Haskell/Practical_monads#Make_a_monad_over_state



来源:https://stackoverflow.com/questions/6311512/creating-unique-labels-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!