0

I am writing an (small-step) interpreter for a simple imperative programming language in Haskell. I want to do evaluation outside of the IO monad and I am thus trying to use the ST monad for mutable variables. However I realise that this means introducing a new phantom type variable to my value type, but then my expression type also needs it, and then my statement type also needs it, and so fourth.

My question is, are there any good ways of avoiding this problem. Could I hide the phantom type in some way? I have tried to do this by introducing a forall s. in my AST definitions, but the compiler is never happy with this.

Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
NatureShade
  • 2,187
  • 1
  • 19
  • 27
  • 2
    I don't think this can be achieved without unsafe functions. Using the same `s` everywhere is the way you prove to the compiler that references do not linger after `runST` returned. – chi May 11 '18 at 21:03
  • 2
    There is one other alternative - don't use mutable references in the small-step interpreter. – Carl May 11 '18 at 21:20
  • 1
    Some code from your interpreter would help to explain the problem better. – Artem Pelenitsyn May 11 '18 at 21:56
  • I ended up biting the bullet and introduce the `s` phantom variable everywhere. However now I realise that it impossible to do things the way I want to because I have a value of type `StateT (MyState s) (ST s)` which of course is impossible. – NatureShade May 11 '18 at 22:07
  • Can't you write a function `MyState s -> MyState ()`? If there are no references left, it should be feasible. Even if there are references, the function might be able to remove them, if they are wrapped inside `Maybe` or some other type. – chi May 11 '18 at 22:34
  • 1
    @NatureShade yeah that doesn't seem impossible to me either. It's just `MyState s -> ST s (a, MyState s)` which is a perfectly reasonable function. – luqui May 11 '18 at 22:34
  • @luqi Thank you! Of course I can just generate the initial state and `runStateT` inside the `ST` monad and then use the result inside the same context. – NatureShade May 11 '18 at 23:06

0 Answers0