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

Similar documents
Programming Languages

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

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

Variables and Bindings

Programming Languages

Programming Languages

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

Programming Languages

Begin at the beginning

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

Programming Languages. Datatypes

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

Programming Languages

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

Programming Languages

Recap: Functions as first-class values

Programming Languages

CSE 130 [Winter 2014] Programming Languages

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

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

Programming Languages

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

Programming Languages

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

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

So what does studying PL buy me?

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

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

Typical workflow. CSE341: Programming Languages. Lecture 17 Implementing Languages Including Closures. Reality more complicated

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

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

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

Metaprogramming assignment 3

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.

CSE 341: Programming Languages

CSE 341 Section 5. Winter 2018

Introduction to OCaml

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

Project 2: Scheme Interpreter

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

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

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

Outline. What is semantics? Denotational semantics. Semantics of naming. What is semantics? 2 / 21

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

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

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

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

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

To figure this out we need a more precise understanding of how ML works

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

CMSC 330: Organization of Programming Languages. Lets, Tuples, Records

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

CMSC 330: Organization of Programming Languages

CMSC 336: Type Systems for Programming Languages Lecture 4: Programming in the Lambda Calculus Acar & Ahmed 22 January 2008.

Lists. Prof. Clarkson Fall Today s music: "Blank Space" by Taylor Swift

CS558 Programming Languages

Thinking Induc,vely. COS 326 David Walker Princeton University

Product types add could take a single argument of the product type int * int fun add(,y):int = +y; > val add = fn : int * int -> int add(3,4); > val i

CMSC 330: Organization of Programming Languages. Operational Semantics

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

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

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

Lecture 15 CIS 341: COMPILERS

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

CPSC W1 University of British Columbia

Homework 3 COSE212, Fall 2018

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

Type Checking and Type Inference

CS 11 Haskell track: lecture 1

These are notes for the third lecture; if statements and loops.

CS558 Programming Languages

Types, Type Inference and Unification

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

CMSC 330: Organization of Programming Languages. Rust Basics

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

CS558 Programming Languages

Lambda Calculus: Implementation Techniques and a Proof. COS 441 Slides 15

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

Problem Set CVO 103, Spring 2018

Programming Languages and Compilers (CS 421)

Inductive Data Types

Note that pcall can be implemented using futures. That is, instead of. we can use

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

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

Programming Project #3: Syntax Analysis

CMSC330. Objects, Functional Programming, and lambda calculus

User-defined Functions. Conditional Expressions in Scheme

Announcements. Working on requirements this week Work on design, implementation. Types. Lecture 17 CS 169. Outline. Java Types

Intro. Scheme Basics. scm> 5 5. scm>

CSE341 Autumn 2017, Final Examination December 12, 2017

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

Transcription:

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