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

Similar documents
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

CSE 341: Programming Languages

Programming Languages Dan Grossman Welcome to the Class!

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

Functions. Nate Foster Spring 2018

Begin at the beginning

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

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

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

Introduction to OCaml

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

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

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

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

Programming Languages

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

Programming Languages

CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion. Zach Tatlock Winter 2018

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

Programming Languages

Programming Languages

Programming Languages

Programming Languages

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

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

Preparing for Class: Watch le Videos! What is an ML program?

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013

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 341: Programming Languages

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.

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

Programming Languages

Programming Languages

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

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

Programming Languages

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

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

CSE 341: Programming Languages

Programming Languages

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

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.

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

SML A F unctional Functional Language Language Lecture 19

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

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

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

Fall 2018 Stephen Brookes. LECTURE 2 Thursday, August 30

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

CSE 341 Section 5. Winter 2018

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

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

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

Recap: ML s Holy Trinity

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

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Part I: Written Problems

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

Programming Languages. Datatypes

Homework 3 COSE212, Fall 2018

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

Fall Lecture 3 September 4. Stephen Brookes

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

A Brief Introduction to Standard ML

CMSC 330, Fall 2013, Practice Problem 3 Solutions

Part I: Written Problems

Scheme as implemented by Racket

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

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

If we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

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

A quick introduction to SML

Introduction to OCaml

CMSC 330, Fall 2013, Practice Problems 3

CSCI-GA Scripting Languages

CS 314 Principles of Programming Languages

Data Types. Guest Lecture: Andrew Myers Spring 2018

Example Scheme Function: equal

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

CSci 4223 Principles of Programming Languages

Functional Programming. Pure Functional Programming

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CS 11 Ocaml track: lecture 2

CSE 130 [Winter 2014] Programming Languages

Which of the following expressions has the type int list?

Lists. Michael P. Fourman. February 2, 2010

Lecture 2: SML Basics

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

Types and Programming Languages. Lecture 5. Extensions of simple types

CSE341: Programming Languages Winter 2018 Unit 5 Summary Zach Tatlock, University of Washington

User-defined Functions. Conditional Expressions in Scheme

CSE 374 Programming Concepts & Tools

SML Style Guide. Last Revised: 31st August 2011

Programming Languages and Techniques (CIS120)

Programming Languages and Compilers (CS 421)

So what does studying PL buy me?

CSE341: Programming Languages Lecture 26 Course Victory Lap. Dan Grossman Spring 2016

Transcription:

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

Review Building up SML one construct at a time via precise definitions Constructs have syntax, type-checking rules, evaluation rules And reasons they re in the language Evaluation converts an expression to a value So far: Variable bindings Several expression forms: addition, conditionals, Several types: int bool unit Today: Brief discussion on aspects of learning a PL Functions, pairs, and lists [almost enough for all of HW1] 2

Five different things 1. Syntax: How do you write language constructs? 2. Semantics: What do programs mean? (Evaluation rules) 3. Idioms: What are typical patterns for using language features to express your computation? 4. Libraries: What facilities does the language (or a well-known project) provide standard? (E.g., file access, data structures) 5. Tools: What do language implementations provide to make your job easier? (E.g., REPL, debugger, code formatter, ) These are 5 separate issues In practice, all are essential for good programmers Many people confuse them, but shouldn t 3

Our Focus This course focuses on semantics and idioms Syntax is usually uninteresting A fact to learn, like The American Civil War ended in 1865 People obsess over subjective preferences [yawn] Libraries and tools crucial, but often learn new ones on the job We re learning language semantics and how to use that knowledge to do great things 4

Function definitions Functions: the most important building block in the whole course Like Java methods, have arguments and result But no classes, this, return, etc. Example function binding: (* Note: correct only if y>=0 *) fun pow (x : int, y : int) = if y=0 then 1 else x * pow(x,y-1) Note: The body includes a (recursive) function call: pow(x,y-1) 5

Function bindings: 3 questions Syntax: fun x0 (x1 : t1,, xn : tn) = e (Will generalize in later lecture) Evaluation: A function is a value! (No evaluation yet) Adds x0 to environment so later expressions can call it (Function-call semantics will also allow recursion) Type-checking: Adds binding x0 : (t1 * * tn) -> t if: Can type-check body e to have type t in the static environment containing: Enclosing static environment x1 : t1,, xn : tn x0 : (t1 * * tn) -> t (for recursion) (earlier bindings) (arguments with their types) 6

More on type-checking fun x0 (x1 : t1,, xn : tn) = e New kind of type: (t1 * * tn) -> t Result type on right The overall type-checking result is to give x0 this type in rest of program (unlike Java, not for earlier bindings) Arguments can be used only in e (unsurprising) Because evaluation of a call to x0 will return result of evaluating e, the return type of x0 is the type of e The type-checker magically figures out t if such a t exists Later lecture: Requires some cleverness due to recursion More magic after hw1: Later can omit argument types too 7

Function Calls A new kind of expression: 3 questions Syntax: e0 (e1,,en) (Will generalize later) Parentheses optional if there is exactly one argument Type-checking: If: e0 has some type (t1 * * tn) -> t e1 has type t1,, en has type tn Then: e0(e1,,en) has type t Example: pow(x,y-1) in previous example has type int 8

Function-calls continued Evaluation: e0(e1,,en) 1. (Under current dynamic environment,) evaluate e0 to a function fun x0 (x1 : t1,, xn : tn) = e Since call type-checked, result will be a function 2. (Under current dynamic environment,) evaluate arguments to values v1,, vn 3. Result is evaluation of e in an environment extended to map x1 to v1,, xn to vn ( An environment is actually the environment where the function was defined, and includes x0 for recursion) 9

Example, extended fun pow (x : int, y : int) = if y=0 then 1 else x * pow(x,y-1) fun cube (x : int) = pow (x,3) val sixtyfour = cube 4 val fortytwo = pow(2,4) + pow(4,2) + cube(2) + 2 10

Some gotchas Three common gotchas Bad error messages if you mess up function-argument syntax The use of * in type syntax is not multiplication Example: int * int -> int In expressions, * is multiplication: x * pow(x,y-1) Cannot refer to later function bindings That s what the rules say Helper functions must come before their uses Need special construct for mutual recursion (later) 11

Recursion If you re not yet comfortable with recursion, you will be soon Will use for most functions taking or returning lists Makes sense because calls to same function solve simpler problems Recursion more powerful than loops We won t use a single loop in ML Loops often (not always) obscure simple, elegant solutions 12

Tuples and lists So far: numbers, booleans, conditionals, variables, functions Now ways to build up data with multiple parts This is essential Java examples: classes with fields, arrays Rest of lecture: Tuples: fixed number of pieces that may have different types Lists: any number of pieces that all have the same type Later: Other more general ways to create compound data 13

Pairs (2-tuples) We need a way to build pairs and a way to access the pieces Build: Syntax: (e1,e2) Evaluation: Evaluate e1 to v1 and e2 to v2; result is (v1,v2) A pair of values is a value Type-checking: If e1 has type t1 and e2 has type t2, then the pair expression has type t1 * t2 A new kind of type, the pair type 14

Pairs (2-tuples) We need a way to build pairs and a way to access the pieces Access: Syntax: #1 e and #2 e Evaluation: Evaluate e to a pair of values and return first or second piece Example: If e is a variable x, then look up x in environment Type-checking: If e has type ta * tb, then #1 e has type ta and #2 e has type tb 15

Examples Functions can take and return pairs fun swap (pr : int*bool) = (#2 pr, #1 pr) fun sum_two_pairs (pr1 : int*int, pr2 : int*int) = (#1 pr1) + (#2 pr1) + (#1 pr2) + (#2 pr2) fun div_mod (x : int, y : int) = (x div y, x mod y) 16

Tuples Actually, you can have tuples with more than two parts A new feature: a generalization of pairs (e1,e2,,en) t1 * t2 * * tn #1 e, #2 e, #3 e, Homework 1 uses triples of type int*int*int a lot 17

Nesting Pairs and tuples can be nested however you want Not a new feature: implied by the syntax and semantics val x1 = (7,(true,9)) (* int * (bool*int) *) val x2 = #1 (#2 x1)) (* bool *) val x3 = (#2 x1) (* bool*int *) val x4 = ((3,5),((4,8),(0,0))) (* (int*int)*((int*int)*(int*int)) *) 18

Lists Despite nested tuples, the type of a variable still commits to a particular amount of data In contrast, a list can have any number of elements But unlike tuples, all elements have the same type Need ways to build lists and access the pieces 19

Building Lists The empty list is a value: [] In general, a list of values is a value; elements separated by commas: [v1,v2,,vn] If e1 evaluates to v and e2 evaluates to a list [v1,,vn], then e1::e2 evaluates to [v,,vn] e1::e2 (* pronounced cons *) 20

Accessing Lists Until we learn pattern-matching, we will use three standard-library functions null e evaluates to true if and only if e evaluates to [] If e evaluates to [v1,v2,,vn] then hd e evaluates to v1 (raise exception if e evaluates to []) If e evaluates to [v1,v2,,vn] then tl e evaluates to [v2,,vn] (raise exception if e evaluates to []) Notice result is a list 21

Type-checking list operations Lots of new types: For any type t, the type t list describes lists where all elements have type t Examples: int list bool list int list list (int * int) list (int list * int) list So [] can have type t list list for any type SML uses type a list to indicate this ( quote a or alpha ) For e1::e2 to type-check, we need a t such that e1 has type t and e2 has type t list. Then the result type is t list null : a list -> bool hd : a list -> a tl : a list -> a list 22

Example list functions fun sum_list (lst : int list) = if null lst then 0 else hd(lst) + sum_list(tl(lst)) fun countdown (x : int) = if x=0 then [] else x :: countdown (x-1) fun append (lst1 : int list, lst2 : int list) = if null lst1 then lst2 else hd (lst1) :: append (tl(lst1), lst2) 23

Recursion again Functions over lists are usually recursive Only way to get to all the elements What should the answer be for the empty list? What should the answer be for a non-empty list? Typically in terms of the answer for the tail of the list! Similarly, functions that produce lists of potentially any size will be recursive You create a list is out of smaller lists 24

Lists of pairs Processing lists of pairs requires no new features. Examples: fun sum_pair_list (lst : (int*int) list) = if null lst then 0 else #1(hd lst) + #2(hd lst) + sum_pair_list(tl lst) fun firsts (lst : (int*int) list) = if null lst then [] else #1(hd lst) :: firsts(tl lst) fun seconds (lst : (int*int) list) = if null lst then [] else #2(hd lst) :: seconds(tl lst) fun sum_pair_list2 (lst : (int*int) list) = (sum_list (firsts lst)) + (sum_list (seconds lst)) 25