Warning! It seems that you are using Dodona within another webpage, so not everything may work properly. Let your teacher know so that he can solve the problem by adjusting a setting in the learning environment. In the meantime, you can click this link to open Dodona in a new window.
Warning! The page was not fully loaded, probably because of a network issue. It could be that not all functionalities work as expected. Please try reloading the page.
Haskell exercise
Monadische interpreter
Sign in to hand in your solution and get feedback.
-- Een lambdacalculus
--------------------------------------------------------------------------------
-- Een variabelenaam
type Name = String
-- Een term in de lambdacalculus
data Term = Var Name
| Con Int
| Add Term Term
| Lam Name Term
| App Term Term
-- Een waarde in de lambdacalculus
data Value = Wrong -- De term was ongeldig
| Num Int -- Een getal
| Fun (Value -> M Value) -- Een monadische functie
-- De evaluatieomgeving: variabelenamen gecombineerd met hun waarde
type Environment = [(Name,Value)]
-- Een waarde afdrukken
instance Show Value where
show Wrong = "<wrong>"
show (Num i) = show i
show (Fun f) = "<function>"
-- Een eigen monad
--------------------------------------------------------------------------------
-- M is de identity monad
type M a = undefined
unitM :: a -> M a
unitM x = undefined
bindM :: M a -> (a -> M b) -> M b
x `bindM` k = undefined
showM :: (Show a) => M a -> String
showM x = undefined
-- De monadische interpreter
--------------------------------------------------------------------------------
-- Zoek een variabele op in de omgeving
lookUp :: Name -> Environment -> M Value
lookUp x [] = unitM Wrong
lookUp x ((y,b):e) = if x == y then unitM b else lookUp x e
-- Tel twee getalwaarden op
add :: Value -> Value -> M Value
add (Num i) (Num j) = unitM (Num (i+j))
add _ _ = unitM Wrong
-- Pas een functiewaarde toe op een argumentwaarde
apply :: Value -> Value -> M Value
apply (Fun k) x = k x
apply _ _ = unitM Wrong
-- Bereken de waarde van een term gegeven een omgeving
interp :: Term -> Environment -> M Value
interp (Var x) e = lookUp x e
interp (Con i) e = unitM (Num i)
interp (Add u v) e = interp u e `bindM` (\a ->
interp v e `bindM` (\b ->
add a b))
interp (Lam x v) e = unitM (Fun (\a -> interp v ((x,a):e)))
interp (App t u) e = interp t e `bindM` (\f ->
interp u e `bindM` (\a ->
apply f a))
-- Een term uitrekenen en afdrukken
test :: Term -> String
test t = showM (interp t [])