Subst & Mutators
Table of Contents
1. Subst
{def f1 {(a) => {+ {f2 4} a}}} {def f2 {(b) =? {* a b}}}
Subst {f1 3} = {+ {f2 4} 3} = {+ {* a 4} 3} -> at this point we error because in the scope ’a’ does not exist
a = “unbound identifer”
lexical scop/static scope - I can read the funciton definitions and any variable within can be traced back.
- EX: where ’a’ cant not be used like it is above
- we get this for free in substitute
vs.
Dynamic Scope (a mistake) - where ’a’ character can be used between function calls
2. mutators
2.1. Map
Apply a function to everything in a list, and return a new list where every element has been modifed
EXAMPLE:
List Comprehension in Python
def double(lst : list[int]) -> list[int]: return [2 * x for x in lst]
In Racket
(define (double-all [lst : (Listof Integer)]) : (Listof Integer) (for/list ([x lst]) (* 2 x)))
If we had a double function we can use map…
(define (double [x : Integer]) : Integer (* 2 x)) (map double '(1 2 3))
2.2. Filter
Filters a list and returns new list of contents that fit the requirements
(filter even? '(2 7 3 5 6 3)) = '(2 6)
2.3. Fold
Smash values in a list until you reach on single piece of information
Uses
- add up all values in a list (sum)
- multiply all values in list (product)
- min
- max
base case for fold we have to explicitly say.
sum : (fold + 0 ’(1 2 3))
consider : (fold - 0 ’(1 2))
there are two ways we can interpret this…
2 - (1 - 0)
1 - (2 - 0)
so we need foldl and foldr; specifying what side to start on.
2.4. Why we care
’{func {+ 1 2} {* 3 4} 17}
in the parse…
(match exp . . . [(list (? valid-id? f) args …) (AppC f (map parse args))])
2.5. Mutation
2.6. Environment vs. Subst
{def f {(x) => {+ {* 3 x} x}}}
{f 5} Environment
= {+ {* 3 x} x} ; x is 5 = {+ {* 3 5} x} ; x is 5 = {+ {* 3 5} x} ; x is 5 = {+ 15 x} ; “” = {+ 15 5} ; “” = 20
now IdC do not contain a character but instead a lookup key.
what about from before
{f1 3}
{+ {f2 4} a} ; a is 3 {+ {* a b} a} ; a is 3, b is 4 —> this is wrong f2 should not know what a is
So we are going to need to have different environments for different piececs.