turion / rhine

Haskell Functional Reactive Programming framework with type-level clocks
http://hackage.haskell.org/package/rhine
124 stars 21 forks source link

Allow to specify constraints on the internal state of an automaton? #338

Open turion opened 5 months ago

turion commented 5 months ago

In https://github.com/turion/essence-of-live-coding/ there is a type that is very similar to AutomatonT, but it differs by having the Data constraint on the internal state. This was an arbitrary decision, and any other serialization type with sufficient introspection would be suitable as well, e.g. Generic, or maybe even IsAcidic (see https://github.com/turion/essence-of-live-coding/issues/124). There might also be other constraints that give useful features.

The idea is to generalise StreamT (and thus all other types) to include one more type level argument c:

data CStreamT c m a = forall s. c s =>
  CStreamT
  { state :: s
  , step :: s -> m (Result s a)
  }

Instantiating c at Data would then give the current implementation of essence-of-live-coding, allowing to refactor it and reduce the code base. Instantiating it at IsAcidic gives applications whose state can be persisted using acid-state, and so on.

The downside is that this changes a lot of type signatures. It might be possible to create a type alias and use this:

type StreamT m a = CStream () m a

But it's unclear how ergonomic this is, since still all functions need to be written in the more general style.

For some functions, the type signature is even more restricted. Whenever state is added, we need to make sure the whole state is an instance of the type class. E.g. the type signature of feedback might now be:

feedback ::
  (Functor m, c s, (forall s' . c s' => c (ResultState s s'))) =>
  -- | The additional internal state
  s ->
  -- | The original automaton
  Automaton m (a, s) (b, s) ->
  Automaton m a b
turion commented 5 months ago

Another great example would be adding a kind of CRDT constraint on the internal state. Then it is conceivable that we could run two copies of the same program on different machines, constantly synchronising their state.