News. Programming Languages. Recap. Recap: Environments. Functions. of functions: Closures. CSE 130 : Fall Lecture 5: Functions and Datatypes

Similar documents
Programming Languages

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function

Programming Languages

Recap. Recap. If-then-else expressions. If-then-else expressions. If-then-else expressions. If-then-else expressions

Programming Languages

Programming Languages. Next: Building datatypes. Suppose I wanted. Next: Building datatypes 10/4/2017. Review so far. Datatypes.

Programming Languages

Programming Languages. Datatypes

Recap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.

CSE 130 Programming Languages. Datatypes. Ranjit Jhala UC San Diego

CSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego

Recap: ML s Holy Trinity

Programming Languages

Begin at the beginning

CSE 130 [Winter 2014] Programming Languages

Programming Languages

Programming Languages

Variables and Bindings

Side note: Tail Recursion. Begin at the beginning. Side note: Tail Recursion. Base Types. Base Type: int. Base Type: int

Tail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial

Programming Languages

News. CSE 130: Programming Languages. Environments & Closures. Functions are first-class values. Recap: Functions as first-class values

Programming Languages

Programming Languages

Recap: Functions as first-class values

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

Programming Languages

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

OCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD*

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter

Project 2: Scheme Interpreter

Programming Languages Lecture 14: Sum, Product, Recursive Types

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018

So what does studying PL buy me?

Any questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)

CSE 341 Section 5. Winter 2018

CVO103: Programming Languages. Lecture 5 Design and Implementation of PLs (1) Expressions

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Dan Grossman Fall 2011

Programming Languages Lecture 15: Recursive Types & Subtyping

sum: tree -> int sum_leaf: tree -> int sum_leaf: tree -> int Representing Trees Next: Lets get cosy with Recursion Sum up the leaf values. E.g.

Today s Plan. Programming Languages. Example : Factorial. Recursion. CSE 130 : Spring Lecture 6: Higher-Order Functions

CS558 Programming Languages

CSE 341: Programming Languages

CS Lecture 5: Pattern Matching. Prof. Clarkson Fall Today s music: Puff, the Magic Dragon by Peter, Paul & Mary

Mini-ML. CS 502 Lecture 2 8/28/08

CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions. Dan Grossman Spring 2013

CSE 341: Programming Languages

A Programming Language. A different language g is a different vision of life. CSE 130 : Fall Two variables. L1: x++; y--; (y=0)?

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

CSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Functional Programming

Programming Languages

Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CS558 Programming Languages

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

Data Types The ML Type System

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CS558 Programming Languages

Lecture 3: Recursion; Structural Induction

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Programming Languages

SCHEME AND CALCULATOR 5b

Scope and Introduction to Functional Languages. Review and Finish Scoping. Announcements. Assignment 3 due Thu at 11:55pm. Website has SML resources

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.

Bindings & Substitution

Programming Languages. Tail Recursion. CSE 130: Winter Lecture 8: NOT TR. last thing function does is a recursive call

Fall Lecture 3 September 4. Stephen Brookes

Cunning Plan. One-Slide Summary. Functional Programming. Functional Programming. Introduction to COOL #1. Classroom Object-Oriented Language

CMSC 330: Organization of Programming Languages. Formal Semantics of a Prog. Lang. Specifying Syntax, Semantics

Redefinition of an identifier is OK, but this is redefinition not assignment; Thus

CSE413 Midterm. Question Max Points Total 100

Fall 2018 Lecture N

Homework 3 COSE212, Fall 2018

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures

CSE 341: Programming Languages

Programming Languages and Compilers (CS 421)

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Metaprogramming assignment 3

A Programming Language. A different language g is a different vision of life. CSE 130 : Spring Two variables. L1: x++; y--; (y=0)?

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

Background. CMSC 330: Organization of Programming Languages. Useful Information on OCaml language. Dialects of ML. ML (Meta Language) Standard ML

Type Checking and Type Inference

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Lecture #23: Conversion and Type Inference

CSE341 Autumn 2017, Final Examination December 12, 2017

User-defined Functions. Conditional Expressions in Scheme

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

Introduction to OCaml

Programming Languages. Example 5. Example 4. CSE 130 : Fall type, can reuse code for all types! let rec cat l = match l with

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

Transcription:

CSE 130 : Fall 2007 Programming Languages News PA deadlines shifted PA #2 now due 10/24 (next Wed) Lecture 5: Functions and Datatypes Ranjit Jhala UC San Diego Recap: Environments Phone book Variables = names = phone number 1. Evaluate: Find and use most recent value of variable 2. Extend: let x = e Add new binding at end of phone book Recap Variables are names for values Environment: dictionary/phonebook Most recent binding used Entries never changed, new entries added Environment frozen at fun definition Re-binding variables cannot change a function Same I/O behavior at every call 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 expression 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 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 Binding used to eval (f ) x 4 : int f fn <code, >: int->int x 8 : int Binding for subsequent x 1

Free (vs. Bound) Variables Nested function bindings let a = 20 let f x = let y = 1 in let g z = y + z in a + (g x) f 0 Inside a function: A bound occurrence: 1. Formal variable 2. Variable bound in let-in x, a, z are bound inside f A free occurrence: Not bound occurrence a is free inside f Environment at definition, frozen inside closure, is used for values of free variables let a = 20 let f x = let a = 1 in let g z = a + z in a + (g x) f 0; Inside a function: A bound occurrence: 1. Formal variable 2. Variable bound in let-in-end x, a, z are bound inside f A free occurrence: Not bound occurrence nothing is free inside f Environment at definition, frozen inside closure, is used for values of free variables Nested function bindings of function application let a = 20 let f x = let a = 1+1 in let g z = a + z in a + (g x) f 0; Q: Where do values of bound variables come from? Bound variable values determined when fun evaluated ( executed ) From arguments Local variable bindings Obtained from evaluation 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 x + body e), env is E 2. Evaluate e2 in current env to get (argument) v2 3. Evaluate body e in env E extended by binding x to v2 Example 1 let x = 1 let f y = x + y let x = 2 let y = 3 y f (x + y) 2

Example 2 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) Q: Closure value (Code + Env)? Code: Formal: z Body expr: x + y + z Frozen Environment: x bound to 2 y bound to 4 Example 3 let f g = let x = 0 in g 2 let x = 100 let h y = x + y f h 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 programy Very useful for readability, debugging: Don t have to figure out where a variable got assigned Unique, statically known definition for each occurrence What about more complex data? Expressions Types Many kinds of expressions: 1. Simple 2. Variables 3. Functions What about more complex data? We ve seen some base types and values: Integers, Floats, Bool, String etc. 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 Next: Building datatypes Three key ways to build complex 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 3

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) Many 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 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 box labeled C1 Or a value of type t2 placed in a box labeled C2 Or Or a value of type tn placed in a box labeled Cn Suppose I wanted Creating Attributes: Name(string) Age (integer) DOB (int-int-int) t t) Address (string) Height (real) Alive (boolean) Phone (int-int) email (string) type attrib = Height of float Email of string How to create values of type attrib? # let a1 = Name Ranjit val x : attrib = Name Ranjit # 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 = Height of float Email of string One-of types 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 Suppose I want a function to print attribs datatype attrib = Height of real Email of string; How to tell whats in the box? type attrib = Height of float Email of string 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 expression: check if e is of the form On match: value in box bound to pattern variable matching result expression is evaluated Simultaneously test and extract contents of box 4

Case-of is an Expression 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 expression: check if e is of the form On match: value in box bound to pattern variable matching result expression is evaluated Simultaneously test and extract contents of box match-with is an Expression C1 x1 -> e1 C2 x2 -> e2 Cn xn -> en Type rules? e1, e2,,en must have same type Which is type of whole expression Benefits of match-with What about Recursive types? C1 x1 -> e1 C2 x2 -> e2 Cn xn -> en type t = C1 of t1 C2 of t2 Cn of tn type int_list = Nil Cons of int * int_list 1. Simultaneous test-extract-bind 2. Compile-time checks for: missed cases: ML warns if you miss a t value redundant cases: ML warns if a case never matches Think about this! What are values of int_list? Cons(1,Cons(2,Cons(3,Nil))) Cons(2,Cons(3,Nil)) Cons(3,Nil) Nil Cons Cons Cons 1, 2, 3, Nil Lists aren t built-in! Some functions on Lists : Length datatype int_list = Nil Cons of int * int_list Base pattern Ind pattern let rec len l = match l with Nil -> 0 Cons(h,t) -> 1 + (len t) Base Expression Inductive Expression 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 Nil let rec len l = match l with Nil -> 0 Cons(_,t) -> 1 + (len t) Matches everything, no binding let rec len l = match l with Cons(_,t) => 1 + (len t) _ -> 0 Pattern-matching in order - Must match with Nil 5

Some functions on Lists : Append Base pattern Ind pattern let rec append (l1,l2) = Find the right induction strategy Base case: pattern + expression Induction case: pattern + expression Base Expression Inductive Expression Well designed datatype gives strategy null, hd, tl are all functions Bad ML style: More than aesthetics! Pattern-matching better than test-extract: ML checks all cases covered ML checks no redundant cases at compile-time: fewer errors (crashes) during execution get the bugs out ASAP! Another Example: Calculator We want an arithmetic calculator to evaluate expressions 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 ML datatype for such expressions? Another Example: Calculator We want an arithmetic calculator to evaluate expressions like: 4.0 + 2.9 = 6.9 3.78 5.92 = -2.14 (4.0 + 2.9) * (3.78-5.92) = -14.766 Whats a ML function for evaluating such expressions? Random Art from Expressions PA #2 Build more funky expressions, evaluate them, to produce: 6