问题
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