# CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Save this PDF as:

Size: px
Start display at page:

Download "CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey"

## Transcription

1 CS 3110 Lecture 6: Map and Fold Prof. Clarkson Spring 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey

2 Review Course so far: Syntax and semantics of (most of) OCaml Today: No new language features New idioms: Map, fold, and other higher-order functions

3 Question #1 How much of PS1 have you finished? A. None B. About 25% C. About 50% D. About 75% E. I m done!!!

4 Review: higher-order functions Functions are values Can use them anywhere we use values Arguments, results, parts of tuples, bound to variables, carried by datatype constructors or exceptions, First-class citizens of language, afforded all the rights of any other values Functions can take functions as arguments Functions can return functions as results functions can be higher-order 4

5 Review: anonymous functions (aka function expressions) Syntax: fun x -> e really fun p -> e Type checking: Conclude that fun x -> e : t1 -> t2 if e:t2 under assumption x:t1 Evaluation: A function is already a value

6 Lambda In PL, anonymous functions a.k.a. lambda expressions λx. e The lambda means what follows is an anonymous function x is its argument e is its body Just like fun x -> e, but slightly different syntax Standard feature of any functional language (ML, Haskell, Scheme, ) You ll see lambda show up in many places in PL, e.g.: PHP: A popular PL blog: Lambda style: 6

7 Review: currying Recall: every OCaml function takes exactly one argument Can encode n arguments with one n-tuple Or, can write function that takes one argument and returns a function that takes another argument and Called currying after famous logician Haskell vs. Curry 7

8 Haskell B. Curry Languages Haskell and Curry named for him Curry-Howard isomorphism: Types are logical formulas Programs are logical proofs fun x -> x : 'a -> 'a 8

9 HUGE HIGHER-ORDER FUNCTIONS Discovery of the monolith:

10 Map bad style! map (fun x -> shirt_color(x)) [ ] = [gold, blue, red] 10

11 Map map shirt_color [ ] = [gold, blue, red] how would you implement map? 11

12 Map let rec map f xs = match xs with [] -> [] x::xs -> (f x)::(map f xs ) map : ('a -> 'b) -> 'a list -> 'b list Map is HUGE: You use it all the time once you know it Exists in standard library as List.map, but the idea can be used in any data structure (trees, stacks, queues ) 12

13 Question #2 What is value of lst after this code? let is_even x = (x mod 2 = 0) let lst = map is_even [1;2;3;4] A. [1;2;3;4] B. [2;4] C. [false; true; false; true] D. false E. None of the above

14 Question #2 What is value of lst after this code? let is_even x = (x mod 2 = 0) let lst = map is_even [1;2;3;4] A. [1;2;3;4] B. [2;4] C. [false; true; false; true] D. false E. None of the above

15 Filter filter is_vulcan [ ] = [ ] (er, half vulcan) how would you implement filter? 15

16 Filter let rec filter f xs = match xs with [] -> [] x::xs -> if f x then x::(filter f xs ) else filter f xs filter : ('a -> bool) -> 'a list -> 'a list Filter is also HUGE In library: List.filter 16

17 Question #3 What is value of lst after this code? let is_even x = (x mod 2 = 0) let lst = filter is_even [1;2;3;4] A. [1;2;3;4] B. [2;4] C. [false; true; false; true] D. false

18 Question #3 What is value of lst after this code? let is_even x = (x mod 2 = 0) let lst = filter is_even [1;2;3;4] A. [1;2;3;4] B. [2;4] C. [false; true; false; true] D. false

19 Iterators Map and filter are iterators Not built-in to the language, an idiom Benefit of iterators: separate recursive traversal from data processing Can reuse same traversal for different data processing Can reuse same data processing for different data structures leads to modular, maintainable, beautiful code! So far: iterators that change or omit data what about combining data? e.g., sum all elements of list 19

20 Fold v1.0 Idea: stick an operator between every element of list folding [1;2;3] with (+)! becomes 1+2+3! -->*! 6!

21 Fold v2.0 Idea: stick an operator between every element of list But list could have 1 element, so need an initial value folding [1] with 0 and (+)! becomes 0+1! -->*! 1!

22 Fold v2.0 Idea: stick an operator between every element of list But list could have 1 element, so need an initial value folding [1;2;3] with 0 and (+)! becomes ! -->*! 6!

23 Fold v2.0 Idea: stick an operator between every element of list But list could have 1 element, so need an initial value Or list could be empty; just return initial value folding [] with 0 and (+)! becomes 0!

24 Question #4 What should the result of folding [1;2;3;4] with 1 and ( * ) be? A. 1 B. 24 C. 10 D. 0 E. None of the above

25 Question #4 What should the result of folding [1;2;3;4] with 1 and ( * ) be? A. 1 B. 24 C. 10 D. 0 E. None of the above

26 Fold v3.0 Idea: stick an operator between every element of list But list could have 1 element, so need an initial value Or list could be empty; just return initial value Implementation detail: iterate left-to-right or right-to-left? folding [1;2;3] with 0 and (+)! left to right becomes: ((0+1)+2)+3...fold_left! right to left becomes: 1+(2+(3+0))...fold_right! Both evaluate to 6; does it matter? Yes: not all operators are associative e.g. subtraction, division, exponentiation,

27 Question #5 Result of fold_right with input list [1;2;3], initial accumulator 1 and operator (-)? A. -5 B. -1 C. 1 D. Operator has the wrong type E. None of the above

28 Question #5 Result of fold_right with input list [1;2;3], initial accumulator 1 and operator (-)? A. -5 B. -1 C. 1 D. Operator has the wrong type E. None of the above

29 Question #6 Result of fold_left with input list [1;2;3], initial accumulator 1 and operator (-)? A. -5 B. -1 C. 1 D. Operator has the wrong type E. None of the above

30 Question #6 Result of fold_left with input list [1;2;3], initial accumulator 1 and operator (-)? A. -5 B. -1 C. 1 D. Operator has the wrong type E. None of the above

31 Fold v4.0 (+) accumulated a result of the same type as list itself What about operators that change the type? e.g., let cons x xs = x::xs cons : 'a -> 'a list -> 'a list! folding from the right [1;2;3] with [] and cons! should produce 1::(2::(3::[])) = [1;2;3]! So the operator needs to accept the accumulated result so far, and the next element of the input list which may have different types!

32 Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b!

33 Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b! Operator mnemonic: operator takes in accumulator on the (left right)

34 Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b! Input list

35 Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b! Initial value of accumulator mnemonic: fold takes in accumulator on the (left right) of the list

36 Fold for real Two versions in OCaml library: List.fold_left! : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a!!! List.fold_right! : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b! Final value of accumulator

37 fold_left! let rec fold_left f acc xs = match xs with [] -> acc x::xs -> fold_left f (f acc x) xs Accumulates an answer by repeatedly applying f to answer so far, starting with initial value acc,! folding from the left fold_left f acc [a;b;c]! computes f (f (f acc a) b) c! 37

38 fold_right! let rec fold_right f xs acc = match xs with [] -> acc x::xs -> f x (fold_right f xs acc) Accumulates an answer by repeatedly applying f to answer so far, starting with initial value acc,! folding from the right fold_right f [a;b;c] acc! computes f a (f b (f c acc))! 38

39 Behold the HUGE power of fold Implement so many other functions with fold! let rev xs = fold_left (fun xs x -> x::xs) [] xs let length xs = fold_left (fun a _ -> a+1) 0 xs let map f xs = fold_right (fun x a -> (f x)::a) xs [] let filter f xs = fold_right (fun x a -> if f x then x::a else a) xs [] 39

40 Beware the efficiency of fold Implementation of fold_left more space efficient than fold_right for long lists what is "long"? maybe 10,000 elements But that doesn t mean that one is strictly better than the other More in recitation

41 Map-Reduce Fold has many synonyms/cousins in various functional languages, including scan and reduce! Google organizes large-scale data-parallel computations with Map-Reduce open source implementation by Apache called Hadoop [Google s Map-Reduce] abstraction is inspired by the map and reduce primitives present in Lisp and many other functional languages. We realized that most of our computations involved applying a map operation to each logical record in our input in order to compute a set of intermediate key/value pairs, and then applying a reduce operation to all the values that shared the same key in order to combine the derived data appropriately." [Dean and Ghemawat, 2008]

### CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CS 3110 Lecture 6: Map and Fold Prof. Clarkson Fall 2014 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Features so far: variables, operators, let expressions, if expressions,

### CSci 4223 Principles of Programming Languages

CSci 4223 Principles of Programming Languages Lecture 11 Review Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matching,

### Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421d # true;; - : bool = true # false;; - : bool =

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

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Sasa Misailovic 4110 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421a # true;; - : bool = true # false;; - : bool

### Lecture 4: Higher Order Functions

Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function

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

CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,

### CS3110 Spring 2016 Lecture 6: Modules

CS3110 Spring 2016 Lecture 6: Modules Modules are the O part of OCaml, influenced by objects in Java. We see the evolution: Classic ML, CambridgeML (CAML), and finally OCaml. David McQueen is writing the

### Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Lecture 10 February 5 th, 2016 Abstract types: sets Lecture notes: Chapter 10 What is the value of this expresssion? let f (x:bool) (y:int) : int = if x then

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

CS 3110 Lecture 5: Pattern Matching Prof. Clarkson Fall 2014 Today s music: Puff, the Magic Dragon by Peter, Paul & Mary Review Features so far: variables, operators, let expressions, if expressions, functions

### List Functions, and Higher-Order Functions

List Functions, and Higher-Order Functions Björn Lisper Dept. of Computer Science and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ List Functions, and Higher-Order

### CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

CS152: Programming Languages Lecture 7 Lambda Calculus Dan Grossman Spring 2011 Where we are Done: Syntax, semantics, and equivalence For a language with little more than loops and global variables Now:

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

CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh

### SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

### Review. CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Let bindings (CBV) Adding Stuff. Booleans and Conditionals

Review CS152: Programming Languages Lecture 11 STLC Extensions and Related Topics e ::= λx. e x ee c v ::= λx. e c (λx. e) v e[v/x] e 1 e 2 e 1 e 2 τ ::= int τ τ Γ ::= Γ,x : τ e 2 e 2 ve 2 ve 2 e[e /x]:

### COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

### CMSC330. Objects, Functional Programming, and lambda calculus

CMSC330 Objects, Functional Programming, and lambda calculus 1 OOP vs. FP Object-oriented programming (OOP) Computation as interactions between objects Objects encapsulate mutable data (state) Accessed

### Whereweare. CS-XXX: Graduate Programming Languages. Lecture 7 Lambda Calculus. Adding data structures. Data + Code. What about functions

Whereweare CS-XXX: Graduate Programming Languages Lecture 7 Lambda Calculus Done: Syntax, semantics, and equivalence For a language with little more than loops and global variables Now: Didn t IMP leave

### Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in

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

Racket Next 2+ weeks will use the Racket language (not ML) and the DrRacket programming environment (not emacs) Installation / basic usage instructions on course website CSE34: Programming Languages Lecture

### CSE341 Spring 2016, Midterm Examination April 29, 2016

CSE341 Spring 2016, Midterm Examination April 29, 2016 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please

### COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

### CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 Goals of this tutorial You should be able to... understand

### Some Advanced ML Features

Some Advanced ML Features Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming University of Washington: Dan Grossman ML is small Small number of powerful constructs

### CMSC 330: Organization of Programming Languages. Lambda Calculus

CMSC 330: Organization of Programming Languages Lambda Calculus 1 Turing Completeness Turing machines are the most powerful description of computation possible They define the Turing-computable functions

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

Announcements: What are the following numbers: 52/37/19/6 (2:30,3:35,11:15,7:30) PS2 due Thursday 9/22 11:59PM Quiz #1 back in section Monday Quiz #2 at start of class on Thursday 9/22 o HOP s, and lots

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

Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

### CSE 130 [Winter 2014] Programming Languages

CSE 130 [Winter 2014] Programming Languages Higher-Order Functions! Ravi Chugh! Jan 23 Today s Plan A little more practice with recursion Base Pattern Base Expression Induction Pattern Induction Expression

### Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1

Types of recursion Readings: none. In this module: a glimpse of non-structural recursion CS 135 Winter 2018 07: Types of recursion 1 Structural vs. general recursion All of the recursion we have done to

### CSE 341: Programming Languages

CSE 341: Programming Languages Dan Grossman Spring 2008 Lecture 6 Nested pattern-matching; course motivation Dan Grossman CSE341 Spring 2008, Lecture 6 1 Patterns What we know: case-expresssions do pattern-matching

### Programming Languages Fall 2014

Programming Languages Fall 2014 Lecture 7: Simple Types and Simply-Typed Lambda Calculus Prof. Liang Huang huang@qc.cs.cuny.edu 1 Types stuck terms? how to fix it? 2 Plan First I For today, we ll go back

### Programming Languages Fall 2013

Programming Languages Fall 2013 Lecture 7: Simple Types and Simply-Typed Lambda Calculus Prof. Liang Huang huang@qc.cs.cuny.edu Types stuck terms? how to fix it? Plan First I For today, we ll go back to

### More Untyped Lambda Calculus & Simply Typed Lambda Calculus

Concepts in Programming Languages Recitation 6: More Untyped Lambda Calculus & Simply Typed Lambda Calculus Oded Padon & Mooly Sagiv (original slides by Kathleen Fisher, John Mitchell, Shachar Itzhaky,

### CSCE 314 Programming Languages

CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as

### Concepts of Programming Languages

Concepts of Programming Languages Lecture 15 - Functional Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages

### Lab 7: OCaml 12:00 PM, Oct 22, 2017

CS17 Integrated Introduction to Computer Science Hughes Lab 7: OCaml 12:00 PM, Oct 22, 2017 Contents 1 Getting Started in OCaml 1 2 Pervasives Library 2 3 OCaml Basics 3 3.1 OCaml Types........................................

### CS 11 Ocaml track: lecture 2

Today: CS 11 Ocaml track: lecture 2 comments algebraic data types more pattern matching records polymorphic types ocaml libraries exception handling Previously... ocaml interactive interpreter compiling

### Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

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

News CSE 130: Spring 2012 Programming Languages On webpage: Suggested HW #1 PA #1 (due next Fri 4/13) Lecture 2: A Crash Course in ML Please post questions to Piazza Ranjit Jhala UC San Diego Today: A

### Shell CSCE 314 TAMU. Higher Order Functions

1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.

### Introduction to dependent types in Coq

October 24, 2008 basic use of the Coq system In Coq, you can play with simple values and functions. The basic command is called Check, to verify if an expression is well-formed and learn what is its type.

### The Haskell HOP: Higher-order Programming

The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments

### Modular Programming. Prof. Clarkson Fall Today s music: "Giorgio By Moroder" by Daft Punk

Modular Programming Prof. Clarkson Fall 2017 Today s music: "Giorgio By Moroder" by Daft Punk Moog modular synthesizer Based in Trumansburg, NY, 1953-1971 Game changing! picked up by the Beatles, the Rolling

### Modules and Representation Invariants

Modules and Representation Invariants COS 326 Andrew W. Appel Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel In previous classes: Reasoning about individual OCaml expressions.

### CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

### COMP 1130 Lambda Calculus. based on slides by Jeff Foster, U Maryland

COMP 1130 Lambda Calculus based on slides by Jeff Foster, U Maryland Motivation Commonly-used programming languages are large and complex ANSI C99 standard: 538 pages ANSI C++ standard: 714 pages Java

### More Lambda Calculus and Intro to Type Systems

More Lambda Calculus and Intro to Type Systems Plan Heavy Class Participation Thus, wake up! Lambda Calculus How is it related to real life? Encodings Fixed points Type Systems Overview Static, Dyamic

### CIS 500 Software Foundations Midterm I

CIS 500 Software Foundations Midterm I October 11, 2006 Name: Student ID: Email: Status: Section: registered for the course not registered: sitting in to improve a previous grade not registered: just taking

### Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

### SOFTWARE VERIFICATION AND COMPUTER PROOF (lesson 1) Enrico Tassi Inria Sophia-Antipolis

SOFTWARE VERIFICATION AND COMPUTER PROOF (lesson 1) Enrico Tassi Inria Sophia-Antipolis Who am I? 1. I'm a researcher at Inria 2. I work on proof assistants, the kind of tools that we will be using for

### CSE 307: Principles of Programming Languages

1 / 63 CSE 307: Principles of Programming Languages Syntax R. Sekar Topics 1. Introduction 2. Basics 3. Functions 4. Data Structures 5. Overview 6. OCAML Performance 2 / 63 3 / 63 Section 1 Introduction

### Types, Type Inference and Unification

Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

### CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages Syntax R. Sekar 1 / 63 Topics 1. Introduction 2. Basics 3. Functions 4. Data Structures 5. Overview 6. OCAML Performance 2 / 63 Section 1 Introduction 3 / 63

### CIS 500 Software Foundations Fall September 25

CIS 500 Software Foundations Fall 2006 September 25 The Lambda Calculus The lambda-calculus If our previous language of arithmetic expressions was the simplest nontrivial programming language, then the

### Lists. Michael P. Fourman. February 2, 2010

Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

### Type Checking and Type Inference

Type Checking and Type Inference Principles of Programming Languages CSE 307 1 Types in Programming Languages 2 Static Type Checking 3 Polymorphic Type Inference Version: 1.8 17:20:56 2014/08/25 Compiled

### Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

### Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Spring 2017 Outline Functions State Functions as building blocks Higher order functions Map Reduce

### Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

### Denotational Semantics. Domain Theory

Denotational Semantics and Domain Theory 1 / 51 Outline Denotational Semantics Basic Domain Theory Introduction and history Primitive and lifted domains Sum and product domains Function domains Meaning

### Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

### Introduction to Objective Caml

Introduction to Objective Caml Stefan Wehr University of Freiburg. October 30, 2006 Motivation Simple Expressions and Types Functions Simple Pattern Matching Compound Datatypes I/O and Compilation Resources

### Functional Programming - 2. Higher Order Functions

Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class

### Why OCaml? Introduction to Objective Caml. Features of OCaml. Applications written in OCaml. Stefan Wehr

Motivation Introduction to Objective Caml Why OCaml? Stefan Wehr University of Freiburg. October 30, 2006 Motivation Simple Expressions and Types I/O and Compilation Resources Convenient encoding of tree

### Functional Programming. Introduction To Cool

Functional Programming Introduction To Cool #1 Cunning Plan ML Functional Programming Fold Sorting Cool Overview Syntax Objects Methods Types #2 This is my final day... as your... companion... through

### CS 4110 Programming Languages & Logics. Lecture 28 Recursive Types

CS 4110 Programming Languages & Logics Lecture 28 Recursive Types 7 November 2014 Announcements 2 Foster office hours 11-12pm Guest lecture by Fran on Monday Recursive Types 3 Many languages support recursive

### Programming Languages

CSE 130 : Winter 2013 Programming Languages Lecture 3: Crash Course, Datatypes Ranjit Jhala UC San Diego 1 Story So Far... Simple Expressions Branches Let-Bindings... Today: Finish Crash Course Datatypes

### MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

### Thoughts on Assignment 4 Haskell: Flow of Control

Thoughts on Assignment 4 Haskell: Flow of Control CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, February 27, 2017 Glenn G. Chappell Department of Computer

### Stop coding Pascal. Saturday, April 6, 13

Stop coding Pascal...emotional sketch about past, present and future of programming languages, Python, compilers, developers, Life, Universe and Everything Alexey Kachayev CTO at KitApps Inc. Open source

### Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington

Programming Languages Function-Closure Idioms Adapted from Dan Grossman's PL class, U. of Washington More idioms We know the rule for lexical scope and function closures Now what is it good for A partial

### GADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences]

GADTs Advanced functional programming - Lecture 7 Wouter Swierstra and Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree

### CS 4110 Programming Languages & Logics. Lecture 27 Recursive Types

CS 4110 Programming Languages & Logics Lecture 27 Recursive Types 4 November 2016 Announcements 2 My office hours are at the normal time today but canceled on Monday Guest lecture by Seung Hee Han on Monday

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

Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";

### Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

### Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

### Functional abstraction

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

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

CSci 4223 Lecture 12 March 4, 2013 Topics: Lexical scope, dynamic scope, closures 1 Lexical Scope SML, and nearly all modern languages, follow the Rule of Lexical Scope: the body of a function is evaluated

### Final Exam CSCI 1101 Computer Science I KEY. Wednesday December 16, 2015 Instructor Muller Boston College. Fall 2015

Fal Exam CSCI 1101 Computer Science I KEY Wednesday December 16, 2015 Instructor Muller Boston College Fall 2015 Please do not write your name on the top of this test. Before readg further, please arrange

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

CSE 130: Programming Languages Polymorphism Ranjit Jhala UC San Diego Q: What is the value of res? let f g = let x = 0 in g 2 let x = 100 let h y = x + y let res = f h (a) 0 (b) 2 (c) 100 (d) 102 (e) 12

### According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!

Lecture 7: Haskell CSC 131 Fall, 2014 Kim Bruce According to Larry Wall (designer of PERL): a language by geniuses for geniuses He s wrong at least about the latter part though you might agree when we

### Elixir, functional programming and the Lambda calculus.

Elixir, functional programming and the Lambda calculus. Programming II - Elixir Version Johan Montelius Spring Term 2018 Introduction In this tutorial you re going to explore lambda calculus and how it

### INTRODUCTION TO FUNCTIONAL PROGRAMMING

INTRODUCTION TO FUNCTIONAL PROGRAMMING Graham Hutton University of Nottingham adapted by Gordon Uszkay 1 What is Functional Programming? Opinions differ, and it is difficult to give a precise definition,

### 3. Functional Programming. Oscar Nierstrasz

3. Functional Programming Oscar Nierstrasz Roadmap > Functional vs. Imperative Programming > Pattern Matching > Referential Transparency > Lazy Evaluation > Recursion > Higher Order and Curried Functions

### Functional Programming

Functional Programming COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Original version by Prof. Simon Parsons Functional vs. Imperative Imperative programming

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

CSE 130 Programming Languages Lecture 3: Datatypes Ranjit Jhala UC San Diego News? PA #2 (coming tonight) Ocaml-top issues? Pleas post questions to Piazza Recap: ML s Holy Trinity Expressions (Syntax)

### Typing Data. Chapter Recursive Types Declaring Recursive Types

Chapter 27 Typing Data 27.1 Recursive Types 27.1.1 Declaring Recursive Types We saw in the previous lecture how rec was necessary to write recursive programs. But what about defining recursive types? Recursive

### L R I BACKTRACKING ITERATORS FILLIATRE J C. Unité Mixte de Recherche 8623 CNRS-Université Paris Sud LRI 01/2006. Rapport de Recherche N 1428

L R I BACKTRACKING ITERATORS FILLIATRE J C Unité Mixte de Recherche 8623 CNRS-Université Paris Sud LRI 01/2006 Rapport de Recherche N 1428 CNRS Université de Paris Sud Centre d Orsay LABORATOIRE DE RECHERCHE

### CMSC 330: Organization of Programming Languages. Closures (Implementing Higher Order Functions)

CMSC 330: Organization of Programming Languages Closures (Implementing Higher Order Functions) CMSC330 Spring 2018 1 Returning Functions as Results In OCaml you can pass functions as arguments to map,

### Constraint-based Analysis. Harry Xu CS 253/INF 212 Spring 2013

Constraint-based Analysis Harry Xu CS 253/INF 212 Spring 2013 Acknowledgements Many slides in this file were taken from Prof. Crista Lope s slides on functional programming as well as slides provided by

### A LISP Interpreter in ML

UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,

### CSC324 Functional Programming Efficiency Issues, Parameter Lists

CSC324 Functional Programming Efficiency Issues, Parameter Lists Afsaneh Fazly 1 January 28, 2013 1 Thanks to A.Tafliovich, P.Ragde, S.McIlraith, E.Joanis, S.Stevenson, G.Penn, D.Horton 1 Example: efficiency

### Coq Summer School, Session 2 : Basic programming with numbers and lists. Pierre Letouzey

Coq Summer School, Session 2 : Basic programming with numbers and lists Pierre Letouzey Predened data structures Predened types are actually declared to Coq at load time 1 : Inductive bool := true false.

### Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009

Logic and Computation Lecture 20 CSU 290 Spring 2009 (Pucella) Thursday, Mar 12, 2009 Note that I change the name of the functions slightly in these notes from what I used in class, to be consistent with

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

CSE341: Programming Languages Winter 2018 Unit 5 Summary Zach Tatlock, University of Washington Standard Description: This summary covers roughly the same material as class and recitation section. It can

### 15 212: Principles of Programming. Some Notes on Continuations

15 212: Principles of Programming Some Notes on Continuations Michael Erdmann Spring 2011 These notes provide a brief introduction to continuations as a programming technique. Continuations have a rich

### Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

Generative and accumulative recursion Readings: Sections 25, 26, 27, 30, 31 Some subsections not explicitly covered in lecture Section 27.2 technique applied to strings CS 135 Fall 2017 11: Generative

### 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 Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Datatypes Compile-time Static Types Ranjit Jhala UC San Diego 1. Programmer enters expression

### CS 360: Programming Languages Lecture 12: More Haskell

CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due