2021-01-30 17:09:05 +00:00
|
|
|
module Enviroment where
|
|
|
|
|
|
|
|
import qualified Data.Map as M
|
2021-01-30 21:38:44 +00:00
|
|
|
import Expression
|
2021-01-30 17:09:05 +00:00
|
|
|
import Data.Maybe
|
|
|
|
|
|
|
|
data Enviroment = Enviroment (M.Map String Expr) (Maybe Enviroment)
|
|
|
|
|
2021-01-30 21:38:44 +00:00
|
|
|
-- The base enviroment, that contains the main functions and variables
|
2021-01-30 17:09:05 +00:00
|
|
|
base :: Enviroment
|
|
|
|
base = Enviroment (M.fromList [
|
2021-01-30 21:38:44 +00:00
|
|
|
("id", LambdaE "x" $ VarE "x"), -- Given a expression, returns the same expression
|
|
|
|
("const", LambdaE "x" $ LambdaE "y" $ VarE "x") -- Given two expressions, returns the first expression
|
2021-01-30 17:09:05 +00:00
|
|
|
]) Nothing
|
|
|
|
|
2021-02-02 23:44:23 +00:00
|
|
|
lookupVar :: String -> Enviroment -> Maybe Expr
|
|
|
|
lookupVar var (Enviroment menv upperEnv) = let mExpr = M.lookup var menv in
|
|
|
|
if isNothing mExpr then upperEnv >>= lookupVar var else mExpr
|
2021-01-30 17:09:05 +00:00
|
|
|
|
2021-02-02 23:44:23 +00:00
|
|
|
insertVar :: String -> Expr -> Enviroment -> Enviroment
|
|
|
|
insertVar var expr (Enviroment menv u) = Enviroment (M.insert var expr menv) u
|
2021-01-30 19:21:25 +00:00
|
|
|
|
|
|
|
emptyEnv :: Enviroment
|
|
|
|
emptyEnv = Enviroment M.empty Nothing
|
|
|
|
|
2021-02-02 23:44:23 +00:00
|
|
|
-- Returns a copy of the second enviroment whose upper enviroment is the first
|
2021-01-30 19:21:25 +00:00
|
|
|
extendEnv :: Enviroment -> Enviroment -> Enviroment
|
2021-02-02 23:44:23 +00:00
|
|
|
extendEnv upper (Enviroment menv Nothing) = Enviroment menv (Just upper)
|
|
|
|
extendEnv upper (Enviroment menv (Just upperMenv)) = Enviroment menv (Just $ extendEnv upperMenv upper)
|