Suppose I'm working with code of a stack machine, which can do some simple operations (push constant, add, mul, dup, swap, pop, convert types) on ints and doubles.
Now the program I'm writing takes a description in some other language and translates it into code for this stack machine. I also need to calculate maximum size of the stack.
I suspect it's possible to use the Haskell type checker to eliminate some bugs, e.g.:
- popping from an empty stack
- multiplying doubles using int multiplication
I thought that I could declare, for example:
dup :: Stack (a :%: b) -> Stack (a :%: b :%: b)
int2double :: Stack (a :%: SInt) -> Stack (a :%: SDouble)
and so on. But then I don't know how to generate the code and calculate stack size.
Is it possible to do it like this? And would it be simple/convenient/worth it?
See Chris Okasaki's "Techniques for Embedding Postfix Languages in Haskell": http://www.eecs.usma.edu/webs/people/okasaki/pubs.html#hw02
Also, this:
Since your stack varies in type, you can't pack it into a regular state monad (although you can pack it into a parameterized monad, but that's a different story) but other than that, this should be straightforward, pleasant, and statically checked.