I am trying to model a system that can operate in different modes. Each mode has some associated state of a particular type and this state can be updated or converted to a state value of another mode. I want to represent each mode as a module which contains the update and convert functions.
In Haskell, I might model this using an existential type:
{-# LANGUAGE ExistentialQuantification #-}
data Mode s = forall n. Mode { next :: Mode n, step :: s -> s, advance :: s -> n }
My first attempt in OCaml was to represent Mode
as a module type:
module type MODE = sig
module Next: MODE
type state
val step: state -> state
val advance: state -> Next.state
end
However, this causes an error because the declaration of MODE
is not available while it is being defined.
I also attempted the trick of using a recursive outer module which is assigned to itself:
module rec ModeOuter: sig
module type MODE = sig
module Next: ModeOuter.MODE
type state
val step: state -> state
val advance: state -> Next.state
end
end = ModeOuter
However, this gives me an error as well:
File "./main.ml", line 3, characters 17-31:
3 | module Next: ModeOuter.MODE
^^^^^^^^^^^^^^
Error: Illegal recursive module reference
I am not exactly sure why OCaml considers this module reference illegal. Is there any other way to work around this?
Thanks for any help.