Suppose I'm creating a simple interpreter that can throw errors, e.g.
type Error = String
data Term = Con Int | Div Term Term
eval :: (MonadError Error m) => Term -> m Int
eval (Con a) = return a
eval (Div u v) = do
a <- eval u
b <- eval v
if b == 0 then
throwError "Division by zero"
else
return $ a `div` b
A typical choice of a concrete error handler, would be Either Error
.
runEval :: Term -> Either Error Int
runEval = eval
Suppose now that I want to extend this interpreter to handle non-determinism. For example, I can add a term Choice Term Term
that can either evaluate to its first or second argument.
data Term = Con Int | Div Term Term | Choice Term Term
I could then represent a concrete evaluation as [Either Error Int]
, where each item in the list represents a possible evaluation. However, I'm struggling how I can add the Choice
case to my eval
function without modifying the Con
and Div
cases.
What I tried:
eval :: (MonadError Error m, MonadPlus m) => Term -> m Int
-- The Con and Div cases remain unchanged.
eval (Choice u v) = do
w <- return u `mplus` return v -- pick either u or v
eval w
runEval :: Term -> [Either Error Int]
runEval = runExceptT . eval
However, this only returns the first possible outcome, and doesn't backtrack.
> let t = Con 1 `Div` (Choice (Con 0) (Con 1))
> runEval t
[Left "Division by zero"]
What I expected: [Left "Division by zero", Right 1]
.
What is the right way to combine non-determinism and error-handling?