Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating unique labels in Haskell

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?

like image 786
Viktor Dahl Avatar asked Feb 02 '23 17:02

Viktor Dahl


1 Answers

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.

like image 114
Don Stewart Avatar answered Feb 05 '23 18:02

Don Stewart