I’ve recently come across a nice trick for encoding FSMs (Finite State Machines) in OCaml.
The idea is to use a polymorphic variant to represent the states of the machine. When the machine is described as an explicit list of transitions – as opposed to function as in the above-cited example --, this makes the definition slightly more readable.
For example, instead of writing (using here strings
as state identifiers)
type fsm = {
...
trans: (string * string) list;
...
}
and then define, for example
# let f1 = { ...; trans=["S1","S2"]; ... }
> val f1 : fsm = {...; trans = [("S1", "S2")]; ... }
one writes
type 'state fsm = {
...
trans: ('state * 'state) list;
...
}
and
# let f1 = { ...; trans=[`S1,`S2]; ... }
> val u1 : [> `S1 | `S2 ] fsm = { ...; trans = [(`S1,`S2)]; ...}
which is – arguably – a bit easier to write and read.
The problem, with the second approach, is how do we print (as a string
for example) a textual representation of the machine ?
If the constructors encoding the states had been defined using a “regular” variant, by writing
type state = S1 | S2
for example, one could have used a [@@deriving show]
PPX annotation for that purpose.
But I don’t see how to apply this technique with the approach above – esp. because the type representing the distinct states in not named here.
In fact, I suspect this is just not possible, because this type is here viewed as a polymorphic type parameter.
Am i right or am i missing sth ?
Jocelyn