CSci 4223 Principles of Programming Languages

Size: px
Start display at page:

Download "CSci 4223 Principles of Programming Languages"

Transcription

1 Review CSci 4223 Prciples of Programmg Languages Lecture 8 Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matchg, exceptions Today: Tail recursion, contued Type variables Equality types Type annotations Prof. Clarkson Sprg Recursion Should now be comfortable with recursion: No harder than usg a loop (whatever that is J ) For recursive datatypes, recursion is more elegant than loops: When processg a tree (e.g., evaluate an arithmetic expression) When appg lists TAIL RECURSION Now: How to reason about efficiency of recursion e importance of tail recursion Usg an accumulator to achieve tail recursion Functional programmg idiom (no new syntax/semantics) 3 4 Call-stacks While a program runs, there is a call stack of function calls that have started but not yet returned Callg a function f pushes an stance of f on the stack When a call to f to fishes, it is popped from the stack ese stack-frames store formation like the value of local variables and what is left to do the function Example fun fact n = if n=0 then 1 else n*fact(n-1) val x = fact 3 fact 3 fact 3: 3*_ fact 3: 3*_ fact 3: 3*_ fact 2 fact 2: 2*_ fact 2: 2*_ fact 1 fact 1: 1*_ fact 0 Because of recursion, multiple stack-frames may be calls to the same function fact 3: 3*_ fact 3: 3*_ fact 3: 3*_ fact 3: 3*2 fact 2: 2*_ fact 2: 2*_ fact 2: 2*1 fact 1: 1*_ fact 1: 1*1 5 fact 0: 1 6 1

2 Example Revised e call-stacks fun fact n = let fun aux(n,acc) = if n=0 then acc else aux(n-1,acc*n) aux(n,1) val x = fact 3 fact 3 aux(3,1) aux(2,3) aux(1,6) Still recursive, more complicated, but the result of recursive calls is the result for the caller (no remag multiplication) 7 aux(1,6):_ aux(0,6) aux(1,6):_ aux(0,6):6 aux(1,6):6 aux(2,3):6 Etc. 8 An optimization It is unnecessary to keep around a stack-frame just so it can get a callee s result and return it without any further evaluation ML recognizes these tail calls the compiler and treats them differently: Pop the caller before the call, allowg callee to reuse the same stack space Implementation turns out to be as efficient as a loop Not just ML; any good implementation of functional language does tail-call optimization What really happens fact 3 fun fact n = let fun aux(n,acc) = if n=0 then acc else aux(n-1,acc*n) aux(n,1) val x = fact 3 aux(3,1) aux(2,3) aux(1,6) aux(0,6) 9 10 Moral Tail-recursive calls can be much more efficient But there s a tradeoff: makes code a little harder to read So best done when efficiency is important Another example fun sum xs = x::xs => x + sum xs Methodology to guide transformation of recursive function: Create a helper function that takes an accumulator Old base case becomes itial accumulator New base case becomes fal accumulator fun sum xs = let fun aux(xs,acc) = [] => acc x::xs => aux(xs,x+acc) aux(xs,0)

3 And another fun rev xs = [] => [] x::xs => (rev xs [x] fun rev xs = let fun aux(xs,acc) = [] => acc x::xs => aux(xs,x::acc) aux(xs,[]) List app can be REALLY efficient fun rev xs = [] => [] x::xs => (rev xs [x] For fact and sum, tail-recursion takes less space but still lear time But, non-tail recursive rev is quadratic because each recursive call uses which must traverse the first list (length-1) is almost length*length/2 Moral: especially with recursion Cons is constant-time (and fast), so the accumulator version rocks Is tail-recursive always more efficient? Precise defition of tail call NO. Sometimes recursive functions can t be evaluated a constant amount of space E.g., functions over trees In these cases, the simple recursive approach is best (You could get one recursive call to be a tail call, but rarely worth the complication) 15 If the result of f x is the immediate result for the enclosg function body, then f x is a tail call Can defe this notion more precisely A tail call is a function call tail position If an expression is not tail position, then no subexpressions are In fun f p = e, the body e is tail position If if e1 then e2 else e3 is tail position, then e2 and e3 are tail position (but e1 is not). (Similar for case-expressions) If let b1 bn e is tail position, then e is tail position (but no bdg expressions are) Function-call arguments are not tail position 16 What the difference? Length of a list: fun len (xs: t list) = _::xs => 1 + len xs TYPE VARIABLES & EQUALITY TYPES 17 fun len (xs: strg list) = _::xs => 1 + len xs No algorithmic difference! Would be silly to have to write function for every kd of list type 18 3

4 Type variables to the rescue Another polymorphic function Use type variable to stand place of an arbitrary type: fun len (xs: 'a list) = _::xs => 1 + len xs What is type of list app? fun app (xs,ys) = [] => ys x::xs => x :: app(xs,ys) Just like we use variables to stand place of arbitrary values Creates a polymorphic function ( poly =many, morph =form) Closely related to generics Java Might look like, but is rather less related to, templates C++ You might expect strg list * strg list -> strg list But REPL reports 'a list * 'a list -> 'a list is is okay [such as on your homework]: why? More general e generalization rule for types e type 'a list * 'a list -> 'a list is more general than the type strg list * strg list -> strg list Polymorphic type can be used as any less general type, such as t list * t list -> t list Easy rule you (and the type-checker) can apply without thkg: A type t1 is more general than the type t2 if you can take t1, replace its type variables consistently, and get t2 Example: Replace each 'a with t * t Example: Replace each 'a with bool and each 'b with bool Example: Replace each 'a with bool and each 'b with t But it is not more general than the type t list * strg list -> t list Must replace type variables consistently Equivalence rules for types Equality types Can combe the more general rule with rules for equivalence Use of type synonyms does not matter Order of field names does not matter Example, given type foo = t * t the type {quux : 'b, bar : t * 'a, baz : 'b} is more general than {quux : strg, bar : foo, baz : strg} which is equivalent to {bar : t*t, baz : strg, quux : strg} You might also see type variables with a second quote Example: ''a list * ''a -> bool ese are equality types that arise from usg the = operator e = operator works on lots of types: t, strg, tuples contag all equality types, But not all types: function types, real, e rules for more general are exactly the same except you have to replace an equality-type variable with a type that can be used with = A strange feature of ML because = is special

5 Example (* a * a -> strg *) fun same_thg(x, y) = if x=y then "yes" else "no" (* t -> strg *) fun is_three x = if x=3 then "yes" else "no" (You can ignore the warng about callg polyequal ) TYPE INFERENCE We stopped writg types How does compiler fer? Started off semester writg: fun pow (x : t, y : t) = if y=0 then 1 else x * pow(x,y-1) But recently we ve been leavg off argument types: fun pow (x, y ) = if y=0 then 1 else x * pow(x,y-1) Here s the idea: fun pow (x, y ) = if y=0 then 1 else x * pow(x,y-1) y must be t, sce compared with = to 0 pow must return t, sce then branch returns 1 x must be t, sce multiplied with an t (defe more carefully later lecture) Either way, compiler has been ferrg that return type is t Selectors complicate type ference Pattern matchg simplifies type ference What is the type of argument to this function? What about this function? fun sum_triple t = case t of (x,y,z) => x+y+z fun sum_triple t = #1 t + #2 t + #3 t Error: unresolved flex record (need to know the names of ALL the fields this context). Which is why we had to write fun sum_triple (t:t*t*t) = #1 t + #2 t + #3 t 29 Pattern gives enough hts to compiler to fer type: fun sum_triple t = case triple of (x,y,z) => x+y+z at s why we don t need to write down types anymore And also why we started off writg down types You can add type annotations anywhere you like Instead of e write e:t e :t is an annotation or constrat used by type ference And that s all that the argument types we wrote down ever were 30 5

6 Functions are values FIRST-CLASS FUNCTIONS 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 so functions are higher-order is is not a new language feature; just a consequence of choice we made long ago when we said functions are values Example Can reuse n_times rather than defg many similar functions Computes f(f( f(x))) where number of calls is n fun n_times (f,n,x) = if n=0 then x else f (n_times(f,n-1,x)) fun double x = x + x fun crement x = x + 1 val x1 = n_times(double,4,7) val x2 = n_times(crement,4,7) val x3 = n_times(tl,2,[4,8,12,16,20]) fun double_n_times (n,x) = n_times(double,n,x) fun nth_tail (n,x) = n_times(tl,n,x) 33 6

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

CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion. Zach Tatlock Winter 2018 CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Zach Tatlock Winter 2018 Nested patterns We can nest patterns as deep as we want Just like we can nest expressions as deep

More information

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

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 7 First-Class Functions Dan Grossman Winter 2013 What is functional programming? Functional programming can mean a few different things: 1. Avoiding mutation in most/all

More information

Tail Recursion and Accumulators

Tail Recursion and Accumulators Tail Recursion and Accumulators Recursion Should now be comfortable with recursion: No harder than using a loop (Maybe?) OAen much easier than a loop When processing a tree (e.g., evaluate an arithmefc

More information

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

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

More information

CSE 341 : Programming Languages Midterm, Spring 2015

CSE 341 : Programming Languages Midterm, Spring 2015 Name: CSE 341 : Programming Languages Midterm, Spring 2015 Please do not turn the page until 12:30. Rules: Closed book, closed note, except for one side of one 8.5x11in piece of paper. Please stop promptly

More information

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

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey CS 3110 Lecture 6: Map and Fold Prof. Clarkson Spring 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Course so far: Syntax and semantics of (most of) OCaml Today: No

More information

CSci 4223 Principles of Programming Languages

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,

More information

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

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,

More information

Functions Over Lists. Programming Languages and Compilers (CS 421) Structural Recursion. Functions Over Lists. Structural Recursion : List Example

Functions Over Lists. Programming Languages and Compilers (CS 421) Structural Recursion. Functions Over Lists. Structural Recursion : List Example Functions Over Lists Programmg Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC http://courses.engr.illois.edu/cs421 Based part on slides by Mattox Beckman, as updated by Vikram Adve and Gul

More information

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

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

Factorial. Next. Factorial. How does it execute? Tail recursion. How does it execute? More on recursion. Higher-order functions

Factorial. Next. Factorial. How does it execute? Tail recursion. How does it execute? More on recursion. Higher-order functions Next More on recursion Higher-order functions takg and returng functions Factorial let rec fact n = Along the way, will see map and fold 1 2 Factorial let rec fact n = if n

More information

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

Preparing for Class: Watch le Videos! What is an ML program? Why are we here? CSE 341 : Programmg Languages Lecture 3 Local Bdgs, Options, Purity Zach Tatlock Sprg 2014 To work together to free our mds from the shackles of imperative programmg. 2 Preparg for Class:

More information

Next. Tail Recursion: Factorial. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial.

Next. Tail Recursion: Factorial. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial. Next Tail Recursion: Factorial More on recursion Higher-order functions takg and returng functions Along the way, will see map and fold let rec fact n = if n

More information

About coding style Spring February 9, 2004

About coding style Spring February 9, 2004 About codg style 15-212 Sprg 2004 February 9, 2004 Contents 1 Correctness 2 2 Specification 2 3 Style 2 3.1 if-then- Expressions... 3 3.1.1 Boolean if-then- Expressions... 3 3.1.2 if-then- stead of Pattern

More information

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

More information

FUNCTIONAL PROGRAMMING

FUNCTIONAL PROGRAMMING FUNCTIONAL PROGRAMMING Map, Fold, and MapReduce Prof. Clarkson Summer 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Yesterday: Lists: OCaml's awesome built-in datatype

More information

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack Forward recursion CS 321 Programming Languages Intro to OCaml Recursion (tail vs forward) Baris Aktemur Özyeğin University Last update made on Thursday 12 th October, 2017 at 11:25. Much of the contents

More information

Today. Recap from last Week. Factorial. Factorial. How does it execute? How does it execute? More on recursion. Higher-order functions

Today. Recap from last Week. Factorial. Factorial. How does it execute? How does it execute? More on recursion. Higher-order functions Recap from last Week Three key ways to build complex types/values 1. Each-of types Value of T contas value of T1 and a value of T2 2. One-of types Value of T contas value of T1 or a value of T2 Today More

More information

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

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016 CSE341: Programming Languages Lecture 11 Type Inference Dan Grossman Spring 2016 Type-checking (Static) type-checking can reject a program before it runs to prevent the possibility of some errors A feature

More information

CSE 341 : Programming Languages

CSE 341 : Programming Languages CSE 341 : Programming Languages Lecture 9 Lexical Scope, Closures Zach Tatlock Spring 2014 Very important concept We know function bodies can use any bindings in scope But now that functions can be passed

More information

A Crash Course on Standard ML

A Crash Course on Standard ML A Crash Course on Standard ML Hongwei Xi Version of November 23, 2004 1 Start Type sml-cm at a Unix wdow to get an teractive terpreter for Standard ML (SML). You can later quit the terpreter by typg ctrl-d.

More information

CSE341 Spring 2016, Midterm Examination April 29, 2016

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

More information

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

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018 CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Winter 2018 Function definitions Functions: the most important building block in the whole course Like Java methods, have arguments

More information

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

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018 Function definitions CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Zach Tatlock Winter 2018 Functions: the most important building block in the whole course Like Java methods, have arguments

More information

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

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Dan Grossman Fall 2011 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,

More information

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341, Fall 2011, Midterm Examination October 31, 2011 CSE341, Fall 2011, Midterm Examination October 31, 2011 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.

More information

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

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

More information

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

Mini-ML. CS 502 Lecture 2 8/28/08 Mini-ML CS 502 Lecture 2 8/28/08 ML This course focuses on compilation techniques for functional languages Programs expressed in Standard ML Mini-ML (the source language) is an expressive core subset of

More information

CSE341 Spring 2016, Midterm Examination April 29, 2016

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

More information

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011 CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Fall 2011 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

More information

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

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

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

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

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

More information

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 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,

More information

CS 11 Ocaml track: lecture 2

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

More information

Higher-Order Functions

Higher-Order Functions Higher-Order Functions Tjark Weber Functional Programming 1 Based on notes by Pierre Flener, Jean-Noël Monette, Sven-Olof Nyström Tjark Weber (UU) Higher-Order Functions 1 / 1 Tail Recursion http://xkcd.com/1270/

More information

CSCI-GA Final Exam

CSCI-GA Final Exam CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

List Functions, and Higher-Order 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

More information

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

CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions. Dan Grossman Spring 2013 CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2013 Five different things 1. Syntax: How do you write language constructs? 2. Semantics: What do programs

More information

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

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,

More information

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

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

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

Exercises on ML. Programming Languages. Chanseok Oh

Exercises on ML. Programming Languages. Chanseok Oh Exercises on ML Programming Languages Chanseok Oh chanseok@cs.nyu.edu Dejected by an arcane type error? - foldr; val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b - foldr (fn x=> fn y => fn z => (max

More information

CSE341 Autumn 2017, Midterm Examination October 30, 2017

CSE341 Autumn 2017, Midterm Examination October 30, 2017 CSE341 Autumn 2017, Midterm Examination October 30, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

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) 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

More information

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

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

More information

Lists. Michael P. Fourman. February 2, 2010

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

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

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

More information

Lecture 6: Sequential Sorting

Lecture 6: Sequential Sorting 15-150 Lecture 6: Sequential Sorting Lecture by Dan Licata February 2, 2012 Today s lecture is about sorting. Along the way, we ll learn about divide and conquer algorithms, the tree method, and complete

More information

CSE 130 [Winter 2014] Programming Languages

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

More information

The Haskell HOP: Higher-order Programming

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

More information

Part I: Written Problems

Part I: Written Problems CSci 4223 Homework 3 DUE: Friday, March 22, 11:59 pm Instructions. Your task is to answer 2 written problems, and to write 16 SML functions (excluding local helper functions) as well as test cases for

More information

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

Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey Map and Fold Prof. Clarkson Fall 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Question How much progress have you made on A1? A. I'm still figuring out how Enigma works.

More information

Some Advanced ML Features

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

More information

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

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

More information

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

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

More information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

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

Programming Languages. Tail Recursion. CSE 130: Winter Lecture 8: NOT TR. last thing function does is a recursive call CSE 130: Winter 2010 News Programming Languages Lecture 8: Higher-Order Od Functions Ranjit Jhala UC San Diego Today s Plan Finish Static Scoping Tail Recursion last thing function does is a recursive

More information

type environment updated subtype sound

type environment updated subtype sound #1 Type Checkg #2 One-Slide Summary A type environment gives types for free variables. You typecheck a let-body with an environment that has been updated to conta the new let-variable. If an object of

More information

Homework 5. Notes. Turn-In Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7.

Homework 5. Notes. Turn-In Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7. Homework 5 Due Wednesday, 14 March Handout 19 CSCI 334: Spring 2018 Notes This homework has two types of problems: Problems: You will turn in answers to these questions. Pair Programming: This part involves

More information

Programming Languages

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

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

Introduction to OCaml

Introduction to OCaml Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional

More information

Theorem Proving Principles, Techniques, Applications Recursion

Theorem Proving Principles, Techniques, Applications Recursion NICTA Advanced Course Theorem Proving Principles, Techniques, Applications Recursion 1 CONTENT Intro & motivation, getting started with Isabelle Foundations & Principles Lambda Calculus Higher Order Logic,

More information

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

More information

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10 Oct 04, 16 21:55 Page 1/10 * Lecture 02 Infer some type arguments automatically. Set Implicit Arguments. Note that the type constructor for functions (arrow " >") associates to the right: A > B > C = A

More information

CSE341 Spring 2016, Final Examination June 6, 2016

CSE341 Spring 2016, Final Examination June 6, 2016 CSE341 Spring 2016, Final Examination June 6, 2016 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

More information

Programming Languages and Compilers (CS 421)

Programming Languages and Compilers (CS 421) Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC http://courses.engr.illinois.edu/cs421 Based in part on slides by Mattox Beckman, as updated by Vikram Adve and Gul Agha 9/11/17

More information

1 Announcements. 2 Scan Implementation Recap. Recitation 4 Scan, Reduction, MapCollectReduce

1 Announcements. 2 Scan Implementation Recap. Recitation 4 Scan, Reduction, MapCollectReduce Recitation 4 Scan, Reduction, MapCollectReduce Parallel and Sequential Data Structures and Algorithms, 15-210 (Sprg 2013) February 6, 2013 1 Announcements How did HW 2 go? HW 3 is out get an early start!

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 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,

More information

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph Topics Functional Programming Christian Sternagel Harald Zankl Evgeny Zuenko Department of Computer Science University of Innsbruck WS 2017/2018 abstract data types, algebraic data types, binary search

More information

CS153: Compilers Lecture 15: Local Optimization

CS153: Compilers Lecture 15: Local Optimization CS153: Compilers Lecture 15: Local Optimization Stephen Chong https://www.seas.harvard.edu/courses/cs153 Announcements Project 4 out Due Thursday Oct 25 (2 days) Project 5 out Due Tuesday Nov 13 (21 days)

More information

Types, Expressions, and States

Types, Expressions, and States 8/27: solved Types, Expressions, and States CS 536: Science of Programming, Fall 2018 A. Why? Expressions represent values in programming languages, relative to a state. Types describe common properties

More information

Type Systems, Type Inference, and Polymorphism

Type Systems, Type Inference, and Polymorphism 6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

More information

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE341, Fall 2011, Midterm Examination October 31, 2011 CSE341, Fall 2011, Midterm Examination October 31, 2011 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.

More information

CMSC 330, Fall 2013, Practice Problems 3

CMSC 330, Fall 2013, Practice Problems 3 CMSC 330, Fall 2013, Practice Problems 3 1. OCaml and Functional Programming a. Define functional programming b. Define imperative programming c. Define higher-order functions d. Describe the relationship

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

Parsing Scheme (+ (* 2 3) 1) * 1

Parsing Scheme (+ (* 2 3) 1) * 1 Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes

More information

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

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

CSc 520. Gofer III. Accumulative Recursion. Accumulative Recursion... Stack Recursion. Principles of Programming Languages. Christian Collberg

CSc 520. Gofer III. Accumulative Recursion. Accumulative Recursion... Stack Recursion. Principles of Programming Languages. Christian Collberg Slide 7 2 Accumulative Recursion We can sometimes get a more efficient solution by giving the function one extra argument, the accumulator, which is used to gather the final result. We will need to use

More information

CS 312, Fall Exam 1

CS 312, Fall Exam 1 Name: ID number: CS 312, Fall 2003 Exam 1 October 16, 2003 Problem 1 2 3 4 Total Grader Grade 18 24 28 30 There are 4 problems on this exam. Please check now that you have a complete exam booklet with

More information

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

# 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

More information

Lecture #24: Programming Languages and Programs

Lecture #24: Programming Languages and Programs Lecture #24: Programming Languages and Programs A programming language is a notation for describing computations or processes. These range from low-level notations, such as machine language or simple hardware

More information

Programming Language Concepts, CS2104 Lecture 7

Programming Language Concepts, CS2104 Lecture 7 Reminder of Last Lecture Programming Language Concepts, CS2104 Lecture 7 Tupled Recursion Exceptions Types, ADT, Haskell, Components 5th Oct 2007 CS2104, Lecture 7 1 Overview 5th Oct 2007 CS2104, Lecture

More information

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

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

More information

Hard deadline: 3/28/15 1:00pm. Using software development tools like source control. Understanding the environment model and type inference.

Hard deadline: 3/28/15 1:00pm. Using software development tools like source control. Understanding the environment model and type inference. CS 3110 Spring 2015 Problem Set 3 Version 0 (last modified March 12, 2015) Soft deadline: 3/26/15 11:59pm Hard deadline: 3/28/15 1:00pm Overview In this assignment you will implement several functions

More information

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

Today s Plan. Programming Languages. Example : Factorial. Recursion. CSE 130 : Spring Lecture 6: Higher-Order Functions CSE 130 : Spring 2011 Programming Languages Lecture 6: Higher-Order Ranjit Jhala UC San Diego Today s Plan A little more practice with recursion Base Pattern -> Base Expression Induction Pattern -> Induction

More information

CSE 341: Programming Languages

CSE 341: Programming Languages CSE 341: Programming Languages Hal Perkins Spring 2011 Lecture 2 Functions, pairs, and lists Hal Perkins CSE341 Spring 2011, Lecture 2 1 What is a programming language? Here are separable concepts for

More information

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides.

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. We are looking for homework graders. If you are interested, send mail to cs242cs.stanford.edu

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

CS 321 Programming Languages

CS 321 Programming Languages CS 321 Programming Languages Intro to OCaml Lists Baris Aktemur Özyeğin University Last update made on Monday 2 nd October, 2017 at 19:27. Some of the contents here are taken from Elsa Gunter and Sam Kamin

More information

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

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)

More information

Parametric types. map: ( a (a b) a list b list. filter: ( a bool) a list a list. Why? a and b are type variables!

Parametric types. map: ( a (a b) a list b list. filter: ( a bool) a list a list. Why? a and b are type variables! What is the deal with a? Parametric types aka: what s up with those a? These meta-functions have strange types: map: ( a b) a list b list filter: ( a bool) a list a list Why? Polymorphism Poly = many,

More information

Typed Scheme: Scheme with Static Types

Typed Scheme: Scheme with Static Types Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit

More information

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

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions CMSC 330: Organization of Programming Languages OCaml Expressions and Functions CMSC330 Spring 2018 1 Lecture Presentation Style Our focus: semantics and idioms for OCaml Semantics is what the language

More information