Docsity

CSE 130: Spring 2012 Lecture 7 - Environments & Closures in ML Programming, Slides of Computer Engineering and Programming

Toggle sidebar
bg1
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)
Func tio ns
Using,
(Taking)
Func tio ns
Parameterized,
similar functions
(e.g. Testers)
Iterator, Accumul,
Reuse computation
pattern w/o
exposing local info
3
Functions are ā€œfirst-classā€ values
• Arguments, return values, bindings …
•What are the benefits ?
Creating,
(Returning)
Func tio ns
Using,
(Taking)
Func tio ns
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.
4
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

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

  1. Evaluate: Use most recent bound value of var
  2. 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

  1. Evaluate: Use most recent bound value of var
  2. 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
  3. Evaluate: Use most recent bound value of var
  4. 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 :

  1. Evaluate expr e1 in env E to get value v : t
  2. 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 :

  1. Evaluate expr e1 in env E to get value v : t
  2. 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 :

  1. Evaluate expr e1 in env E to get value v : t
  2. 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 :
  1. Evaluate expr e1 in env E to get value v : t
  2. 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

  1. Find closure of e
  2. 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
  3. Evaluate e1 in current-env to get ( closure ) = code ( formal x + body e) + env E
  4. Evaluate e2 in current-env to get (argument) v
  5. 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