Recap Epressions (Synta) Compile-time Static Eec-time Dynamic Types (Semantics) Recap Integers: +,-,* floats: +,-,* Booleans: =,<, andalso, orelse, not Strings: ^ 1. Programmer enters epression 2. L checks if epression is well-typed Using a precise set of rules, L tries to find a unique type for the epression meaningful type for the epr 3. L evaluates epression to compute value Of the same type found in step 2 Tuples, Records: #i Fied number of values, of different types Lists: ::,@,hd,tl,null Unbounded number of values, of same type If-then-else epressions if (1 < 2) then 5 else 10 5 if (1 < 2) then [ ab, cd ] else [ ] If-then-else is also an epression! Can use any epression in then, else branch if e1 then e2 else e3 int [ ab, cd ] string list If-then-else epressions if (1 < 2) then 5 else 10 5 if (1 < 2) then [ ab, cd ] else [ ] If-then-else is also an epression! Can use any epression in then, else branch if e1 then e2 else e3 int [ ab, cd ] string list e1 : bool e2: T e3: T if e1 then e2 else e3 : T e1 true e2 v2 if e1 then e2 else e3 v2 e1 false e2 v3 if e1 then e2 else e3 v3 If-then-else epressions if (1 < 2) then [1;2] else 5 if false then [1;2] else 5 then-subep, else-subep must have same type! which is the type of resulting epression e1 : bool e2: T e3: T if e1 then e2 else e3 : T If-then-else epressions e1 : bool e2: T e3: T if e1 then e2 else e3 : T Then-subep, Else-subep must have same type! Equals type of resulting epression if 1>2 then [1,2] else [] [] int list if 1<2 then [] else [ a ] [] string list (if 1>2 then [1,2] else [])=(if 1<2 then [] else [ a ]) 1
Style Eercise Java int foo(i, b, c, d) { if (b) { i++; if (c) { return i + 2; if (d) { i = i + 3; else { return i + 4; return i; OCaml Net: Variables Variables and Bindings Q: How to use variables in L? Q: How to assign to a variable? # let = 2+2;; val : int = 4 let = e;; Bind the value of epression e to the variable Variables and Bindings # let = 2+2;; val : int = 4 # let y = * * ;; val y : int = 64 # let z = [;y;+y];; val z : int list = [4;64;68] Later declared epressions can use ost recent bound value used for evaluation Sounds like C/Java? NO! Environments ( Phone Book ) How L deals with variables Variables = names = phone number Environments and Evaluation L begins in a top-level environment Some names bound let = e;; y z 6 [4;64;68] : int list 8 : int L program = Sequence of variable bindings Program evaluated by evaluating bindings in order 1. Evaluate epr e in current env to get value v : t 2. Etend env to bind to v : t (Repeat with net binding) 2
Environments Eample Phone book Variables = names = phone number 1. Evaluate: Find and use most recent value of variable 2. Etend: Add new binding at end of phone book # let = 2+2;; val : int = 4 # let y = * * ;; val y : int = 64 # let z = [;y;+y];; val z : int list = [4;64;68] # let = + ;; val : int = 8 New binding! y y z y z 6 6 [4;64;68] : int list 6 [4;64;68] : int list 8 : int Environments Environments 1. Evaluate: Use most recent bound value of var 2. Etend: Add new binding at end How is this different from C/Java s store? 1. Evaluate: Use most recent bound value of var 2. Etend: Add new binding at end How is this different from C/Java s store? # let = 2+2;; val : int = 4 # let = 2+2;; val : int = 4 # let f = fun y -> + y; # let = + ; val : int = 8 # f 0; New binding: No change or mutation Old binding frozen in f # let f = fun y -> + y; # let = + ; val : int = 8 # f 0; 8 : int Environments 1. Evaluate: Use most recent bound value of var 2. Etend: Add new binding at end How is this different from C/Java s store? # let = 2+2;; val : int = 4 Cannot change the world Cannot assign to variables Can etend 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 ) # let f = fun y -> + y; # let = + ; val : int = 8 # f 0; Binding used to eval (f ) 8 : int Binding for subsequent Q: Why is this a good thing? # let = 2+2;; val : int = 4 # let f = fun y -> + y;; # let = + ;; val : int = 8; # f 0;; Binding used to eval (f ) 8 : int Binding for subsequent 3
Cannot change the world Q: Why is this a good thing? A: Function behavior frozen at declaration Nothing entered afterwards affects function Same inputs always produce same outputs Localizes debugging Localizes reasoning about the program No sharing means no evil aliasing Eamples of no sharing Remember: No addresses, no sharing. Each variable is bound to a fresh instance of a value Tuples, Lists Efficient implementation without sharing? There is sharing and pointers but hidden from you Compiler s job is to optimize code Efficiently implement these no-sharing semantics Your job is to use the simplified semantics Write correct, cleaner, readable, etendable systems Function bindings Functions are values, can bind using val let fname = fun -> e ;; Problem: Can t define recursive functions! fname is bound after computing rhs value no (or old ) binding for occurences of fname inside e let rec fname = e ;; Occurences of fname inside e bound to this definition let rec fac = if <=1 then 1 else *fac (-1) Recap: Environments Phone book Variables = names = phone number 1. Evaluate: Find and use most recent value of variable 2. Etend: let = e ;; Add new binding at end of phone book What about more comple data? What about more comple data? Epressions We ve seen some base types and values: Integers, Floats, Bool, String etc. Types any kinds of epressions: 1. Simple 2. Variables 3. Functions Some ways to build up types: Products (tuples), records, lists Functions Design Principle: Orthogonality Don t clutter core language with stuff Few, powerful orthogonal building techniques Put derived types, values, functions in libraries 4
Net: Building datatypes Three key ways to build comple types/values 1. Each-of types Value of T contains value of T1 and a value of T2 2. One-of types Value of T contains value of T1 or a value of T2 3. Recursive Value of T contains (sub)-value of same type T Suppose I wanted a program that processed lists of attributes Name (string) Age (integer) DOB (int-int-int) Address (string) Height (float) Alive (boolean) Phone (int-int) email (string) any kinds of attributes: too many to put in a record can have multiple names, addresses, phones, emails etc. Want to store them in a list. Can I? Constructing Datatypes Suppose I wanted type t = C1 of t1 C2 of t2 Cn of tn t is a new datatype. A value of type t is either: a value of type t1 placed in a bo labeled C1 Or a value of type t2 placed in a bo labeled C2 Or Or a value of type tn placed in a bo labeled Cn Attributes: Name (string) Age (integer) DOB (int-int-int) Address (string) Height (real) Alive (boolean) Phone (int-int) email (string) type attrib = Name of string Age of int DOB of int*int*int Address of string Height of float Alive of bool Phone of int*int Email of string;; Creating One-of types How to create values of type attrib? # let a1 = Name John ;; val : attrib = Name John # let a2 = Height 5.83;; val a2 : attrib = Height 5.83 # let year = 1977 ;; val year : int = 1977 # let a3 = DOB (9,8,year) ;; val a3 : attrib = DOB (9,8,1977) # let a_l = [a1;a2;a3];; val a3 : attrib list = type attrib = Name of string Age of int DOB of int*int*int Address of string Height of float Alive of bool Phone of int*int Email of string;; We ve defined a one-of type named attrib Elements are one of: string, int, int*int*int, float, bool Can create uniform attrib lists datatype attrib = Name of string Age of int DOB of int*int*int Address of string Height of real Alive of bool Phone of int*int Email of string; Suppose I want a function to print attribs 5
How to tell whats in the bo? type attrib = Name of string Age of int DOB of int*int*int Address of string Height of float Alive of bool Phone of int*int Email of string;; match e with Name s -> e1 Age i -> e2 DOB (m,d,y) -> e3 Address addr -> e4 Height h -> e5 Alive b -> e6 Phone (a,n) -> e7 Email e -> e8 Pattern-match epression: check if e is of the form On match: value in bo bound to pattern variable matching result epression is evaluated Simultaneously test and etract contents of bo match-with is an Epression match e with C1 1 -> e1 C2 2 -> e2 Cn n -> en Type rules? e1, e2,,en must have same type Which is type of whole epression Benefits of match-with What about Recursive types? match e with C1 1 -> e1 C2 2 -> e2 Cn n -> en type t = C1 of t1 C2 of t2 Cn of tn type int_list = Cons of int * int_list 1. Simultaneous test-etract-bind 2. Compile-time checks for: missed cases: L warns if you miss a t value redundant cases: L warns if a case never matches What about Recursive types? Think about this! What are values of int_list? Cons(1,Cons(2,Cons(3,))) type int_list = Cons of int * int_list Cons(2,Cons(3,)) Cons 1, Cons 2, Cons(3,) Cons 3, Lists aren t built-in! datatype int_list = Cons of int * int_list Lists are a derived type: built using elegant core! 1. Each-of 2. One-of 3. Recursive :: is just a pretty way to say Cons [] is just a pretty way to say 6
Some functions on Lists : Length Some functions on Lists : Append Base pattern Ind pattern let rec len l = match l with -> 0 Cons(h,t) -> 1 + (len t) Base Epression Inductive Epression Base pattern Ind pattern let rec append (l1,l2) = Base Epression Inductive Epression let rec len l = match l with -> 0 Cons(_,t) -> 1 + (len t) let rec len l = match l with Cons(_,t) -> 1 + (len t) _ -> 0 Find the right induction strategy Base case: pattern + epression Induction case: pattern + epression atches everything, no binding Pattern-matching in order - ust match with Well designed datatype gives strategy null, hd, tl are all functions Bad L style: ore than aesthetics! Pattern-matching better than test-etract: L checks all cases covered L checks no redundant cases at compile-time: fewer errors (crashes) during eecution get the bugs out ASAP! Another Eample: Calculator We want an arithmetic calculator to evaluate epressions like: 4.0 + 2.9 = 6.9 3.78 5.92 = -2.14 (4.0 + 2.9) * (3.78-5.92) = -14.766 Q: Whats a L datatype for such epressions? Another Eample: Calculator We want an arithmetic calculator to evaluate epressions like: 4.0 + 2.9 = 6.9 3.78 5.92 = -2.14 (4.0 + 2.9) * (3.78-5.92) = -14.766 Random Art from Epressions PA #2 Build more funky epressions, evaluate them, to produce: Whats a L function for evaluating such epressions? 7
Net: Functions Functions Two questions about function values: Epressions What is the value: Types 1. of a function? Q: What s the value of a function? 2. of a function application (call)? (e1 e2) Functions of functions: Closures Two questions about function values: What is the value: 1. of a function? 2. of a function application (call)? (e1 e2) Body epression not evaluated until application but type-checking takes place at compile time i.e. when function is defined Function value = <code + environment at definition> closure # let = 2+2;; val : int = 4 # let f = fun y -> + y;; # let = + ;; val : int = 8 # f 0;; Binding used to eval (f ) 8 : int Binding for subsequent of function application Eample 1 Application: fancy word for call (e1 e2) apply the argument e2 to the (function) e1 Application Value: 1. Evaluate e1 in current env to get (function) v1 v1 is code + env code is (formal + body e), env is E 2. Evaluate e2 in current env to get (argument) v2 3. Evaluate body e in env E etended by binding to v2 let = 1;; let f y = + y;; let = 2;; let y = 3;; f ( + y);; 8
Eample 1 let = 1;; let f y = + y;; let = 2;; let y = 3;; f ( + y);; Eample 2 let = 1;; let f y = let = 2 in fun z -> + y + z ;; let = 100;; let g =(f 4);; let y = 100;; (g 1);; Eample 2 let = 1;; let f y = let = 2 in fun z -> + y + z ;; let = 100;; let g =(f 4);; let y = 100;; (g 1);; Eample 3 let f g = let = 0 in g 2 ;; let = 100;; let h y = + y;; f h;; Static/Leical Scoping For each occurrence of a variable, Unique place in program tet where variable defined ost recent binding in environment Static/Leical: Determined from the program tet Without eecuting the programy Very useful for readability, debugging: Don t have to figure out where a variable got assigned Unique, statically known definition for each occurrence 9