Library ExtLibExamples.EvalWithExc
Require the monad definitions
Use the instances for exceptions
Strings will be used for error messages
Syntax and values of a simple language
Inductive value : Type :=
| Int : nat -> value
| Bool : bool -> value.
Inductive exp : Type :=
| ConstI : nat -> exp
| ConstB : bool -> exp
| Plus : exp -> exp -> exp
| If : exp -> exp -> exp -> exp.
Section monadic.
| Int : nat -> value
| Bool : bool -> value.
Inductive exp : Type :=
| ConstI : nat -> exp
| ConstB : bool -> exp
| Plus : exp -> exp -> exp
| If : exp -> exp -> exp -> exp.
Section monadic.
Going to work over any monad m that is:
1) a Monad, i.e. Monad m
2) has string-valued exceptions, i.e. MonadExc string m
Use the notation for monads
Import MonadNotation.
Local Open Scope monad_scope.
Local Open Scope monad_scope.
Functions that get nat or bool values from a value
raise ("expected integer got bool")%string
end.
Definition asBool (v : value) : m bool :=
match v with
| Bool b => ret b
| _ => raise ("expected bool got integer")%string
end.
end.
Definition asBool (v : value) : m bool :=
match v with
| Bool b => ret b
| _ => raise ("expected bool got integer")%string
end.
The main evaluator routine returns a value, but since we are
working in the m monad, we return m value
evaluate the sub-terms to numbers
Combine the result
evaluate the test condition to a boolean
case split and perform the appropriate recursion
Some tests
Eval compute in eval (Plus (ConstI 1) (ConstI 2)).
Eval compute in eval (Plus (ConstI 1) (ConstB false)).
Eval compute in eval (Plus (ConstI 1) (ConstB false)).
Other useful monads: