Verifying program correctness using phantom types in Haskell -
suppose i'm working code of stack machine, can simple operations (push constant, add, mul, dup, swap, pop, convert types) on ints , doubles.
now program i'm writing takes description in other language , translates code stack machine. need calculate maximum size of stack.
i suspect it's possible use haskell type checker eliminate bugs, e.g.:
- popping empty stack
- multiplying doubles using int multiplication
i thought declare, example:
dup :: stack (a :%: b) -> stack (a :%: b :%: b) int2double :: stack (a :%: sint) -> stack (a :%: sdouble)
and on. don't know how generate code , calculate stack size.
is possible this? , simple/convenient/worth it?
see chris okasaki's "techniques embedding postfix languages in haskell": http://www.eecs.usma.edu/webs/people/okasaki/pubs.html#hw02
also, this:
{-# language typeoperators #-} module stacks data :* b = :* b deriving show data nilstack = nilstack deriving show infixr 1 :* class stack stacksize :: -> int instance stack b => stack (a :* b) stacksize (_ :* x) = 1 + stacksize x instance stack nilstack stacksize _ = 0 push :: stack b => -> b -> :* b push = (:*) pop :: stack b => :* b -> (a,b) pop (x :* y) = (x,y) dup :: stack b => :* b -> :* :* b dup (x :* y) = x :* x :* y liftbiop :: stack rest => (a -> b -> c) -> :* b :* rest -> c :* rest liftbiop f (x :* y :* rest) = push (f x y) rest add :: (stack rest, num a) => :* :* rest -> :* rest add = liftbiop (+) {- demo: *stacks> stacksize $ dup (1 :* nilstack) 2 *stacks> add $ dup (1 :* nilstack) 2 :* nilstack -}
since stack varies in type, can't pack regular state monad (although can pack parameterized monad, that's different story) other that, should straightforward, pleasant, , statically checked.
Comments
Post a Comment