ITree.Interp.Interp
Interpretable Monads
- The semantics of itrees are given as monad morphisms
itree E ~> M, also called "interpreters".
- "ITree interpreters" (or "itree morphisms") are monad morphisms where the codomain is made of ITrees: itree E ~> itree F.
- In general, "event handlers" are functions E ~> M where
M is a monad.
- "ITree event handlers" are functions E ~> itree F.
Translate
translate h t ≈ interp (trigger ∘ h) t
Definition translateF {E F R} (h : E ~> F) (rec: itree E R -> itree F R) (t : itreeF E R _) : itree F R :=
match t with
| RetF x => Ret x
| TauF t => Tau (rec t)
| VisF e k => Vis (h _ e) (fun x => rec (k x))
end.
Definition translate {E F} (h : E ~> F)
: itree E ~> itree F
:= fun R => cofix translate_ t := translateF h translate_ (observe t).
Arguments translate {E F} h [T].
match t with
| RetF x => Ret x
| TauF t => Tau (rec t)
| VisF e k => Vis (h _ e) (fun x => rec (k x))
end.
Definition translate {E F} (h : E ~> F)
: itree E ~> itree F
:= fun R => cofix translate_ t := translateF h translate_ (observe t).
Arguments translate {E F} h [T].
Interpret
Interpretation schemes can be generalized as a function from a stack of monads T applied to a interpretable monad IM with an indexing I to a semantic domain T M.
Class Interp (IM T: (Type -> Type) -> Type -> Type) (M : Type -> Type) :=
interp : forall (I : Type -> Type) (h: I ~> M), T (IM I) ~> T M.
interp : forall (I : Type -> Type) (h: I ~> M), T (IM I) ~> T M.
Typically, an event handler E ~> M defines a monad morphism itree E ~> M
for any monad M with a loop operator.
This itree interpretation is an instance of the general interpretation scheme.
Definition interp_body {E M : Type -> Type}
{MM : Monad M} {MI : MonadIter M}
(h : E ~> M) :
forall R : Type, itree E R -> M (itree E R + R)%type :=
(fun _ t =>
match observe t with
| RetF r => ret (inr r)
| TauF t => ret (inl t)
| VisF e k => bind (h _ e) (fun x => (ret (inl (k x))))
end).
{MM : Monad M} {MI : MonadIter M}
(h : E ~> M) :
forall R : Type, itree E R -> M (itree E R + R)%type :=
(fun _ t =>
match observe t with
| RetF r => ret (inr r)
| TauF t => ret (inl t)
| VisF e k => bind (h _ e) (fun x => (ret (inl (k x))))
end).
ITrees are an interpretable monad.