# Interpreting Anonymous Functions --- CS 135 // 2021-04-22 ## Administriva - Check in - Assignment 2 should be turned in + I will release assignment 3 at noon today and will no longer accept assignment 2 submissions at that time ## Assignment 3 - Individual assignment - Due Thursday, 4/29 # Questions ## ...about anything? # Review ## The Environment - We can **defer** substitution of identifiers by creating a lookup table mapping names to values - Such a list of bindings is commonly called the **environment** - We will use the following type for this: ```haskell type Env = [(Identifier,Value)] ``` ## Updating `interp` with `Env` - Now our `interp` function will have the following signature: ```haskell interp :: Env -> [FnDef] -> Expr -> Value ``` - We also need a function to lookup a binding: ```haskell lookupEnv :: Identifier -> Env -> Value lookupEnv x [] = error ("*** unbound variable " ++ x) lookupEnv x ((id,val):bs) | x == id = val | otherwise = lookupEnv x bs ``` ## Updating `interp` ```haskell interp :: Env -> [FnDef] -> Expr -> Value interp env fns exp = case exp of ... FnApp f arg -> let (FnDef _ param body) = lookupFn f fs arg' = interp env fs arg env' = (param,arg'):env in interp env' fs body ``` ## Dynamic Scope - Notice that we keep accumulating bindings in our environment every time a function is called - Consider the following functions: ```haskell foo x = bar 1 bar y = x + y ``` - What happens when I call `foo 2` in our language? - This is called **dynamic scope** since the value of a variable depends on the entire history of calls ## Updating `interp` Again ```haskell interp :: Env -> [FnDef] -> Expr -> Value interp env fns exp = case exp of ... FnApp f arg -> let (FnDef _ param body) = lookupFn f fs arg' = interp env fs arg in interp [(param,arg')] fs body ``` - Notice we are forcing functions to use a new environment when they are called - This is called **static scope** so that variables can only depend on their local, lexical scope - Our language now has similar behavior to our substitution interpreter # Functions Anywhere