Download CSE 130: Spring 2012 Lecture 7 - Environments & Closures in ML Programming and more Slides Computer Engineering and Programming in PDF only on Docsity!
CSE 130: Spring 2012
Programming Languages
Lecture 7: Environments & Closures
1 News
2 Recap: Functions as āfirst-classā values
- Arguments, return values, bindings ā¦
- What are the benefits? Creating, (Returning) Functions Using, (Taking) Functions Parameterized, similar functions (e.g. Testers) Iterator, Accumul, Reuse computation pattern w/o exposing local info
Functions are āfirst-classā values
- Arguments, return values, bindings ā¦
- What are the benefits? Creating, (Returning) Functions Using, (Taking) Functions Parameterized, similar functions (e.g. Testers) Iterator, Accumul, Reuse computation pattern w/o exposing local info Compose Functions: Flexible way to build Complex functions from primitives.
Docsity.com
Higher-order funcs enable modular code
- Each part only needs local information
Funcs taking/returning funcs
Data Structure Library list Data Structure Client Uses list Provides meta-functions: map,fold,filter to traverse, accumulate over lists, trees etc. Meta-functions donāt need client info (tester? accumulator ?) Uses meta-functions: map,fold,filter With locally-dependent funs (lt h), square etc. Without requiring Implement. details of data structure 5
Higher-order funcs enable modular code
- Each part only needs local information
āMap-Reduceā et al.
Map-Reduce Client Provides: map, reduce to traverse, accumulate over WWW (āBig Dataā) Distributed across ācloudā Web Analytics āQueriesā Clustering, Page Rank, etc as map/reduce + ops Map-Reduce Library 6
Higher Order Functions
Are Awesome...
Higher Order Functions
..but how do they work
Docsity.com
Environments and Evaluation
ML begins in a ātop-levelā environment
- Some names bound (e.g. +,-, print_string...) let x = e ;;
ML program = Sequence of variable bindings
Program evaluated by evaluating bindings in order
1. Evaluate expr e in current env to get value v : t
2. Extend env to bind x to v : t
(Repeat with next binding)
13 Environments
āPhone bookā
- Variables = ānamesā
- Values = āphone numberā
1. Evaluate:
Find and use most recent value of variable
2. Extend:
Add new binding at end of āphone bookā
14
let x = 2+2;;
val x : int = 4
let y = x * x * x;;
val y : int = 64
let z = [x;y;x+y];;
val z : int list = [4;64;68] # let x = x + x ;; val x : int = 8 Example x 4 : int y 64 : int z [4;64;68] : int list ... ... x 4 : int y 64 : int ... ... x 4 : int ... ... ... ... x 4 : int y 64 : int z [4;64;68] : int list ... ... New binding!^ x^ 8 : int Environments
- Evaluate: Use most recent bound value of var
- Extend: Add new binding at end How is it different from C/Javaās āstoreā?
let x = 2+2;;
val x : int = 4 # let f = fun y -> x + y; val f : int -> int = fn # let x = x + x ; val x : int = 8
f 0;
val it : int = 4 x 4 : int ... ... New binding:
- No change or mutation
- Old binding frozen in^ f x 4 : int f fn < code, >: int->int ... ...
Docsity.com
Environments
- Evaluate: Use most recent bound value of var
- Extend: Add new binding at end
let x = 2+2;
val : int x = 4 # let f = fun y -> x + y; val f : int -> int = fn # let x = x + x ; val x : int = 8; f 0;
val it : int = 4 x 4 : int ... ... x 4 : int f fn < code, >: int->int ... ... x 8 : int x 4 : int f fn < code, >: int->int ... ... How is it different from C/Javaās āstoreā? 17 Environments - Evaluate: Use most recent bound value of var
- Extend: Add new binding at end
let x = 2+2;
val x : int = 4 # let f = fun y -> x + y;; val f : int -> int = fn # let x = x + x ; val x : int = 8
f 0;
val it : int = 4 x 4 : int f fn < code, >: int->int ... ... x 8 : int Binding used to eval (f ā¦) Binding for subsequent x How is it different from C/Javaās āstoreā? 18 Cannot change the world Cannot āassignā to variables
- Can extend the env by adding a fresh binding
- Does not affect previous uses of variable Environment at fun declaration frozen inside fun āvalueā
- Frozen env used to evaluate application (f e) Q: Why is this a good thing?
let x = 2+2;;
val x : int = 4 # let f = fun y -> x + y;; val f : int -> int = fn # let x = x + x ;; val x : int = 8;
f 0;;
val it : int = 4 x 4 : int f fn < code, >: int->int ... ... x 8 : int Binding used to eval (f ā¦) Binding for subsequent x Cannot change the world
Q: Why is this a good thing?
A: Function behavior frozen at declaration
Docsity.com
Local bindings So far: bindings that remain until a re-binding (āglobalā) Local, ātemporaryā variables are useful inside functions
- Avoid repeating computations
- Make functions more readable
let x = e1 in
e
Let-in is an expression! Evaluating let-in in env E :
- Evaluate expr e1 in env E to get value v : t
- Use extended E [ x |-> v : t ] (only) to evaluate e 25 Local bindings
let
x = 10
in
x * x
... ... Evaluating let-in in env E :
- Evaluate expr e1 in env E to get value v : t
- Use extended E [ x |-> v : t ] to evaluate e x 10 : int ... ... ... ...
E
E[x:=10] E 26 Let-in is an expression!
let y =
let
x = 10
in
x * x
... ... Evaluating let-in in env E :
- Evaluate expr e1 in env E to get value v : t
- Use extended E [ x |-> v : t ] to evaluate e x 10 : int ... ... ... ... y 100 : int Nested bindings let x = 10 in (let y = 20 in x * y )
- x ;; Evaluating let-in in env E :
- Evaluate expr e1 in env E to get value v : t
- Use extended E [ x |-> v : t ] to evaluate e ... ... x 10 : int ... ... x 10 : int ... ... y 20 : int x 10 : int ... ... ... ...
Docsity.com
Nested bindings
let
x = 10
in
let
y = 20
in
x * y
let x = 10 in
let y = 20 in
x * y
GOOD Formatting
BAD Formatting
29 Example let rec filter f xs = match xs with | [] -Āā> [] | x::xsā -Āā> let ys = if f x then [x] else [] in let ysā = filter f xs in ys @ ysā 30 Recap 1: Variables are names for values
- Environment: dictionary/phonebook
- Most recent binding used - Entries never change
- New entries added - let-in^ expression - Variable āin-scopeā^ in -expression
- Outside, variable not āin-scopeā Recap 2: Big Exprs With Local Bindings
Docsity.com
Function Application Expressions
Application: fancy word for ācallā
- Function value^ e
- Argument e
- āapplyā argument e2 to function value e
( e1 e2 )
37 Functions Type
The type of any function is:
- T1 : the type of the āinputā
- T2 : the type of the āoutputā
T1 -> T
let fname = fun x - > e
T1 -> T
let fname x = e
T1 -> T 38 Functions Type
The type of any function is:
- T1 : the type of the āinputā
- T2 : the type of the āoutputā
T1, T2 can be any types, including functions!
Whats an example of?
- (^) int -> int
- (^) int * int -> bool
- (^) (int -> int) -> (int -> int)
T1 -> T
of function application
Application: fancy word for ācallā
- āapplyā argument e2 to function value e
( e1 e2 )
Type
e1 : T1 -> T2 e2 : T (e1 e2) : T
- Argument must have same type as āinputā T
- Result has the same type as āoutputā T
Docsity.com
Functions Values
Two questions about function values:
What is the value:
1. ⦠of a function?
2. ⦠of a function āapplicationā (call)? ( e1^ e2 )
fun x -> e
41
Two questions about function values:
What is the value:
1. ⦠of a function? fun x -> e
Values of function = āClosureā
Closure =
Code of Fun. (formal x + body e )
+ Environment at Fun. Definition
42
Two questions about function values:
What is the value:
1. ⦠of a function? fun x -> e
Values of function = āClosureā
Closure =
Code of Fun. (formal x + body e )
+ Environment at Fun. Definition
Values of functions: Closures
(^) Function value = āClosureā
- Body not evaluated until application
- But type-checking when function is defined
let x = 2+2;;
val x : int = 4 # let f = fun y -> x + y ;; val f : int -> int = fn # let x = x + x ;; val x : int = 8
f 0;;
val it : int = 4 x 4 : int f fn < code, >: int->int x 8 : int Binding used to eval (f ā¦) Binding for subsequent x
Docsity.com
Bound values determined when function is evaluated (ācalledā)
- Arguments
- Local variable bindings let a = 20 ;; let f x = let a = 1 in let g z = a + z in a + ( g x ) ; ; f 0; Where do bound-vars values come from? 49
Two questions about function values:
What is the value:
1. ⦠of a function?
2. ⦠of a function āapplicationā (call)? ( e1^ e2 )
fun x -> e
Values of function application āapplyā the argument e2 to the (function) e 50 Values of function application
- Find closure of e
- Execute body of closure with param e Free values found in closure-environment Bound values by executing closure-body Value of a function āapplicationā (call)^ ( e1^ e2 ) Values of function application
- Evaluate e1 in current-env to get ( closure ) = code ( formal x + body e) + env E
- Evaluate e2 in current-env to get (argument) v
- Evaluate body e in env E extended with x := v Value of a function āapplicationā (call)^ ( e1^ e2 )
Docsity.com
let x = 1;; let f y = let x = 2 in fun z -> x + y + z ;; let x = 100;; let g = f 4 ;; let y = 100;; (g 1);; Example
Q: Closure value of g?
formal z
body x + y + z
env [x|->2, y|->4]
Eval body in env extended with formal|-> 1
Eval x+y+z in [x|->2, y|->4,z|->1] ====> 7
53 Example 3
let f g =
let x = 0 in
g 2
let x = 100 ;;
let h y = x + y ;;
f h ;;
54 Static/Lexical Scoping
- For each occurrence of a variable,
- Unique place in program text where variable defined
- Most recent binding in environment
- Static/Lexical: Determined from the program text
- Without executing the program
- Very useful for readability, debugging:
- Donāt have to figure out āwhereā a variable got assigned
- Unique, statically known definition for each occurrence Immutability: The Colbert Principle
āA function behaves the same way on
Wednesday, as it behaved on Monday,
no matter what happened on Tuesday! ā
Docsity.com