Fall 2018 Lecture N

Size: px
Start display at page:

Download "Fall 2018 Lecture N"

Transcription

1 Fall 2018 Lecture N Tuesday, 20 November I m too lazy to figure out the correct number Stephen Brookes

2 midterm2 Mean: 79.5 Std Dev: 18.4 Median: 84

3 today or, we could procrastinate lazy functional programming brought to you (on a plate) by

4 lazy programming Standard ML is call-by-value functions always evaluate their arguments Some other languages are lazy functions may defer argument evaluation until the argument value is needed You can still be lazy in a call-by-value language, but it takes effort!

5 being lazy Defer computation until its result is needed A function value, h : unit -> t (a thunk ) represents a delayed computation for a value of type t To compute the value, call h( ) to force the thunk

6 call-by-value repeat : a list -> a list fun repeat L = repeat L lists are finite repeat evaluates to a function value repeat =>* (fn L => repeat L) repeat [0] doesn t terminate repeat [0] =>* (fn L => repeat L) [0] => repeat [0] =>* repeat [0]) =>*... forever there s no way to build an infinite list

7 lazy lists datatype a lazylist = a thunk Cons of a * (unit -> a lazylist) val Cons = fn - : a * (unit -> a lazylist) -> a lazylist A value of type t lazylist represents an infinite lazy list of values of type t The value has form Cons(v, h), where v : t is the head and h : unit -> t lazylist is (a thunk for) the tail the head is immediately available force h if you need later elements

8 lots of nothing zeros : unit -> int lazylist fun zeros ( ) = Cons(0, zeros) Zeros : int lazylist val Zeros = zeros( ) all ones ones : unit -> int lazylist fun ones ( ) = Cons(1, ones) Ones : int lazylist val Ones = ones( )

9 lazy naturals nats : int -> (unit -> int lazylist) fun nats n ( ) = Cons(n, nats (n+1)) Nats : int lazylist val Nats = Cons(0, nats 1) head tail { Nats represents 0,1,2,3,4,... nats 2 ( ) represents 2,3,4,5,6,...

10 mklazy mklazy : int list -> int lazylist fun mklazy [ ] = Zeros mklazy (x::l) = Cons(x, fn ( ) => mklazy L) Converts an int list to an int lazylist by padding with 0 s

11 representation A value of type t lazylist represents an infinite list of values of type t Zeros Ones nats 42 ( ) represents 0,0,0,0, represents 1,1,1,1, represents 42,43,44,45, mklazy [1,2,3] represents 1,2,3,0,0,0, An expression of type t lazylist represents if it evaluates to a value that represents

12 lazy append append : a list * (unit -> a lazylist) -> a lazylist fun append ([ ], h) = h( ) append (x::xs, h) = Cons(x, fn ( ) => append(xs, h)) What does append([0,1], nats 2) represent? append([0,1], nats 2) =>* Cons(0, h1) where h1( ) =>* Cons(1, h2) and h2( ) =>* Cons(2, h3) and so on append([0,1], nats 2) represents 0,1,2,3,4,

13 think thunks We said append([0,1], nats 2) =>* Cons(0, h1) where h1( ) =>* Cons(1, h2) It s not true that append([0,1], nats 2) =>* Cons(0, fn ( ) => Cons(1, h2)) That s not how ML works! No evaluation inside a function body.

14 lazy append If h( ) represents y0,y1,y2,y3, then append ([x0,,xk], h) represents x0,,xk,y0,y1,y2,y3,

15 repeat repeat : a list -> a lazylist REQUIRES xs [ ] ENSURES repeat(xs) represents xs repeated over and over fun repeat xs = append(xs, fn ( ) => repeat xs) repeat [0] =>*???

16 repeat [0] repeat [0] =>* Cons(0, h0) where h0( ) =>* Cons(0, h1) and h1( ) =>* Cons(0, h2) and so on repeat [0] represents 0,0,0,0,0,...

17 show show : int -> a lazylist -> a list fun show 0 _ = [ ] show n (Cons(x, h)) = x :: show (n-1) (h( )) show 5 (repeat [0]) evaluates to [0,0,0,0,0]

18 lazy equality Lazy list values A and B are equal iff they represent the same infinite sequence For all n, show n A = show n B. Lazy list expressions are equal if they both fail to terminate, or raise the same exception or they evaluate to equal values

19 lazy map map : ( a -> b) -> a lazylist -> b lazylist fun map f (Cons(x, h)) = Cons(f x, fn ( ) => map f (h( ))) map (fn x => x+1) Zeros??? If f is total and L represents x0,x1,x2, recursive call is deferred then map f L represents f(x0),f(x1),f(x2),

20 map is lazy List.map If f : t -> t is total, then for all L : t lazylist, and all n 0, show n (map f L) = List.map f (show n L) PROOF? Use induction on n map f (Cons(x, h)) = Cons(f x, fn ( ) => map f (h( ))) List.map f (x::xs) = (f x) :: List.map f xs show 0 _ = [ ] show n (Cons(x, h)) = x :: show (n-1) (h( ))

21 map is lazy List.map P(n): For all L : t lazylist, all total f, show n (map f L) = List.map f (show n L) THEOREM n 0. P(n) PROOF By induction on n Base: n=0. Both sides are [ ]. Inductive step: n > 0. We show that P(n-1) implies P(n). add justifications for the proof steps Assume IH: P(n-1). Let L be Cons(x, h) and v = f x. show n (map f L) = show n (map f (Cons(x, h))) = show n (Cons(f x, fn () => map f (h()))) = show n (Cons(v, fn () => map f (h()))) = v :: show (n-1) (map f (h())) = v :: List.map f (show (n-1) (h())) = List.map f (x ::(show (n-1) (h()))) = List.map f (show n (Cons(x, h))) = List.map f (show n L) So P(n) holds.

22 lazy map fusion If f and g are total and composable, then for all suitably typed lazy lists L, map (f o g) L = map f (map g L) same as map (f o g) = (map f) o (map g)

23 eager map eager_map : ( a -> b) -> a lazylist -> b lazylist fun eager_map f (Cons(x, h)) = let val L = eager_map f (h( )) in Cons(f x, fn ( ) => L) end eager_map (fn x => x+x) Ones???

24 lazy zip zip : a lazylist * b lazylist -> ( a * b) lazylist fun zip (Cons(x, h), Cons(y, k)) = Cons((x,y), fn ( ) => zip (h( ), k( ))) recursive call is deferred If A represents a0,a1,a2, and B represents b0,b1,b2, then zip(a,b) represents (a0,b0),(a1,b1),(a2,b2),

25 zip is lazy List.zip For all A : t1 lazylist and B : t2 lazylist and all n 0, show n (zip (A, B)) = List.zip (show n A, show n B) PROOF? Use induction on n zip (Cons(x, h), Cons(y, k)) = Cons((x, y), fn ( ) => zip (h( ), k( ))) List.zip (x::xs, y::ys) = (x, y) :: List.zip (xs, ys) show 0 _ = [ ] show n (Cons(x, h)) = x :: show (n-1) (h( ))

26 lazy filter filter : ( a -> bool) -> a lazylist -> a lazylist fun filter p (Cons(x, h)) = if p x then Cons(x, fn ( ) => filter p (h( ))) else filter p (h( )) if x doesn t satisfy p, filter the tail if x satisfies p, x is head of filtered list, defer filtering tail until needed

27 example fun nats n = Cons(n, fn ( ) => nats (n+1)) val Evens = filter (fn x => (x mod 2 = 0)) (nats 0) show 1 Evens = [0] show 2 Evens = [0,2] show 3 Evens = [0,2,4] show 4 Evens = [0,2,4,6] show 5 Evens = [0,2,4,6,8] Evens represents 0,2,4,6,8,10,. the lazy list of all non-negative even integers

28 warning What happens when we evaluate filter (fn x => x<0) (repeat [1])?

29 specification If p is total, L represents a0,a1,a2, and infinitely many ai satisfy p then filter p L represents the lazy list of all the ai that satisfy p For all n 0 there is an N such that show N (filter p L) = the first n elements of L that satisfy p

30 recursive laziness Some lazy lists can be generated recursively natural numbers factorials primes Fibonacci

31 fun facts facts : unit -> int lazylist fun facts( ) = Cons(1, fn ( ) => map (op * ) (zip (facts( ), nats 2 ( )))) facts( ) represents 1, 2, 6, 24, 120, For all n 1, show n (facts( )) = [1!,, n!]

32 lazy stuff To show the power of laziness we tackle some problems that build and manipulate infinite data prime number generation digitwise real arithmetic

33 Primes sift : int -> int lazylist -> int lazylist fun sift x = filter (fn y => y mod x <> 0) sieve : int lazylist -> int lazylist fun sieve (Cons(x, h)) = Cons(x, fn ( ) => sieve (sift x (h( )))) Primes : int lazylist val Primes = sieve(nats 2 ( )) Strike out the twos Strike out the threes...the Sieve of Eratosthenes

34 sift and sieve Suppose Cons(x, h) represents the integers 2 not divisible by the first n primes Then x is the n+1 th prime And sift x (h( )) represents the integers 2 not divisible by the first n+1 primes So sieve(nats 2 ( )) represents the primes

35 reals in decimal Can represent a real number in decimal d0.d1d2...dn... d0 = the integer part 0 dn 9 for n>0 The lazy list d 0, d 1, d2,..., d n,... represents the real number d 0 + (0.1)d 1 + (0.1) 2 d (0.1) n d n +

36 eval10 eval10 : int list -> real fun eval10 [ ] = 0.0 eval10 (x::xs) = real x * eval10 xs eval10 [d 0, d 1, d2,..., d n ] = d 0 + (0.1)d 1 + (0.1) 2 d (0.1) n d n

37 approx10 approx10 : int -> int lazylist -> real fun approx10 n L = eval10 (show (n+1) L) If L represents d 0, d 1, d2..., d n,... then approx10 n L represents d 0 + (0.1)d 1 + (0.1) 2 d (0.1) n d n

38 representing reals L : int lazylist represents r : real if limn (approx10 n L) = r fun zeros( ) = Cons(0, zeros) fun nines( ) = Cons(9, nines) Cons(1, zeros) represents 1.0 Cons(0, nines) represents 1.0

39 validity A lazy list L is valid (decimal) iff all digits in the tail of L are between 0 and 9 Every real number has a valid representation not unique may also have invalid representations 0, 9, 0, 99, 0, 99,... 0, 9, 9, 9, 9, 9,... 1, 0, 0, 0, 0, 0,... invalid valid valid 3 lazy lists, each representing 1.0 : real

40 normality To do lazy real arithmetic, we need ways to build and maintain valid representations carry10 : int lazylist -> int lazylist norm10 : int lazylist -> int lazylist carry10 makes the next digit between 0 and 9 n = 10 * (n div 10) + (n mod 10) 0 n mod 10 9 norm10 makes all digits between 0 and 9, lazily without changing the real number

41 carry10 carry10 : int lazylist -> int lazylist REQUIRES L represents r, digits in tail of L 0 ENSURES carry10(l) represents r, has first tail digit between 0 and 9 fun carry10 (Cons(x, xs)) = let val (Cons(y, ys)) = xs( ) in Cons(x + y div 10, fn ( ) => Cons(y mod 10, ys)) end

42 example L 0, 10, 2, 12, 4, 14, 6,... carry10 L 1, 0, 2, 12, 4, 14, 6,... carry10 (Cons(1, zeros)) = Cons(1, zeros) carry10 (Cons(0, nines)) = Cons(0, nines)

43 norm10 norm10 : int lazylist -> int lazylist REQUIRES L represents r, digits in tail of L between 0 and 18 carry amount 1 ENSURES norm10(l) represents r, all digits in tail are between 0 and 9 fun norm10 (Cons(x, xs)) = let val Cons(y, ys) = xs( ) val N = Cons(x, fn ( ) => norm10 (Cons(y, ys))) in if y+1 < 10 then N else carry10 N end carry amount 1

44 add10 add10 : int lazylist * int lazylist -> int lazylist REQUIRES A represents a, B represents b, digits in tail of A & tail of B are decimal ENSURES add10(a,b) represents a+b, digits in tail are decimal fun add10(a, B) = norm10 (map (op +) (zip(a, B)))

45 example val Y = repeat [0,1,2,3,4,5,6,7,9]; val Z = repeat [0,9]; show 9 (add10(y, Z)); val it = [1,0,3,2,5,4,7,6,9] : int list

46 lessons Reasoning about lazy data is not leisure Need to be careful about termination use specs involving show n for equational reasoning, use lazy notion of equality

Fall Recursion and induction. Stephen Brookes. Lecture 4

Fall Recursion and induction. Stephen Brookes. Lecture 4 15-150 Fall 2018 Stephen Brookes Lecture 4 Recursion and induction Last time Specification format for a function F type assumption guarantee (REQUIRES) (ENSURES) For all (properly typed) x satisfying the

More information

Fall Lecture 3 September 4. Stephen Brookes

Fall Lecture 3 September 4. Stephen Brookes 15-150 Fall 2018 Lecture 3 September 4 Stephen Brookes Today A brief remark about equality types Using patterns Specifying what a function does equality in ML e1 = e2 Only for expressions whose type is

More information

Sometimes it s good to be lazy

Sometimes it s good to be lazy Chapter 8 Sometimes it s good to be lazy Typically, languages such as OCaml (SML, Lisp or Scheme) evaluate expressions by a call-by-value discipline. All variables in OCaml are bound by value, which means

More information

CS 312. Lecture April Lazy Evaluation, Thunks, and Streams. Evaluation

CS 312. Lecture April Lazy Evaluation, Thunks, and Streams. Evaluation CS 312 Lecture 27 29 April 2008 Lazy Evaluation, Thunks, and Streams Evaluation SML as you know it (substitution semantics) if true then e 1 else e 2 e 1 if false then e 1 else e 2 e 2 if eagerly evaluates

More information

ITERATORS AND STREAMS 9

ITERATORS AND STREAMS 9 ITERATORS AND STREAMS 9 COMPUTER SCIENCE 61A November 12, 2015 1 Iterators An iterator is an object that tracks the position in a sequence of values. It can return an element at a time, and it is only

More information

Introduction to Functional Programming: Lecture 7 2 Functions as innite data structures Ordinary ML data structures are always nite. We can, however,

Introduction to Functional Programming: Lecture 7 2 Functions as innite data structures Ordinary ML data structures are always nite. We can, however, Introduction to Functional Programming: Lecture 7 1 Introduction to Functional Programming John Harrison University of Cambridge Lecture 7 Innite data structures Topics covered: Functions as innite data

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

CITS3211 FUNCTIONAL PROGRAMMING. 7. Lazy evaluation and infinite lists

CITS3211 FUNCTIONAL PROGRAMMING. 7. Lazy evaluation and infinite lists CITS3211 FUNCTIONAL PROGRAMMING 7. Lazy evaluation and infinite lists Summary: This lecture introduces lazy evaluation and infinite lists in functional languages. cs123 notes: Lecture 19 R.L. While, 1997

More information

03-25-planned.ml Tue Mar 25 06:32: (* Lecture 14: Infinite data structures *) type a stream = Cons of a * a stream

03-25-planned.ml Tue Mar 25 06:32: (* Lecture 14: Infinite data structures *) type a stream = Cons of a * a stream 03-25-planned.ml Tue Mar 25 06:32:31 2014 1 (* Lecture 14: Infinite data structures *) type a stream = Cons of a * a stream let head (Cons(x, _) : a stream) : a = x let tail (Cons(_, r) : a stream) : a

More information

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

Recap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function CSE 130 : Fall 2011 Recap from last time Programming Languages Lecture 3: Data Types Ranjit Jhala UC San Diego 1 2 A shorthand for function binding Put it together: a filter function # let neg = fun f

More information

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

News. Programming Languages. Recap. Recap: Environments. Functions. of functions: Closures. CSE 130 : Fall Lecture 5: Functions and Datatypes CSE 130 : Fall 2007 Programming Languages News PA deadlines shifted PA #2 now due 10/24 (next Wed) Lecture 5: Functions and Datatypes Ranjit Jhala UC San Diego Recap: Environments Phone book Variables

More information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product

More information

General Computer Science (CH ) Fall 2016 SML Tutorial: Practice Problems

General Computer Science (CH ) Fall 2016 SML Tutorial: Practice Problems General Computer Science (CH08-320101) Fall 2016 SML Tutorial: Practice Problems November 30, 2016 Abstract This document accompanies the traditional SML tutorial in GenCS. It contains a sequence of simple

More information

Lecture 3: Recursion; Structural Induction

Lecture 3: Recursion; Structural Induction 15-150 Lecture 3: Recursion; Structural Induction Lecture by Dan Licata January 24, 2012 Today, we are going to talk about one of the most important ideas in functional programming, structural recursion

More information

CSE 341 Section 5. Winter 2018

CSE 341 Section 5. Winter 2018 CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records

More information

Reasoning about programs. Chapter 9 of Thompson

Reasoning about programs. Chapter 9 of Thompson Reasoning about programs Chapter 9 of Thompson Proof versus testing A proof will state some property of a program that holds for all inputs. Testing shows only that a property holds for a particular set

More information

Australian researchers develop typeface they say can boost memory, that could help students cramming for exams.

Australian researchers develop typeface they say can boost memory, that could help students cramming for exams. Font of all knowledge? Australian researchers develop typeface they say can boost memory, that could help students cramming for exams. About 400 university students took part in a study that found a small

More information

Shell CSCE 314 TAMU. Functions continued

Shell CSCE 314 TAMU. Functions continued 1 CSCE 314: Programming Languages Dr. Dylan Shell Functions continued 2 Outline Defining Functions List Comprehensions Recursion 3 A Function without Recursion Many functions can naturally be defined in

More information

Programming Languages

Programming Languages CSE 130 : Winter 2009 Programming Languages News PA 2 out, and due Mon 1/26 5pm Lecture 5: Functions and Datatypes t UC San Diego Recap: Environments Phone book Variables = names Values = phone number

More information

Cornell University 12 Oct Solutions. (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below.

Cornell University 12 Oct Solutions. (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below. Cornell University 12 Oct 2006 Solutions 1. Types, Polymorphism [14 pts] (parts a b) (a) [9 pts] For each of the 3 functions below, pick an appropriate type for it from the list below. i. fun f x y = (y,

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

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

Call-by-name evaluation

Call-by-name evaluation Lecture IX Keywords: call-by-value, call-by-name, and call-by-need evaluation; lazy datatypes: sequences, streams, trees; lazy evaluation; sieve of Eratosthenes; breadth-first and depth-first traversals.

More information

1 Lazy List Implementation

1 Lazy List Implementation February 3, 2004 lazy.nw 1 1 Lazy List Implementation 1.1 A Simple Implementation lazylist.r Cons

More information

The Worker/Wrapper Transformation

The Worker/Wrapper Transformation The Worker/Wrapper Transformation Andy Gill 1 Graham Hutton 2 1 The University of Kansas 2 The University of Nottingham March 26th, 2009 Andy Gill, Graham Hutton The Worker/Wrapper Transformation March

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

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

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

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

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona The List Datatype CSc 372 Comparative Programming Languages 6 : Haskell Lists Department of Computer Science University of Arizona collberg@gmail.com All functional programming languages have the ConsList

More information

Functional Programming in Haskell Part 2 : Abstract dataypes and infinite structures

Functional Programming in Haskell Part 2 : Abstract dataypes and infinite structures Functional Programming in Haskell Part 2 : Abstract dataypes and infinite structures Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/

More information

FUNCTIONAL PEARLS The countdown problem

FUNCTIONAL PEARLS The countdown problem To appear in the Journal of Functional Programming 1 FUNCTIONAL PEARLS The countdown problem GRAHAM HUTTON School of Computer Science and IT University of Nottingham, Nottingham, UK www.cs.nott.ac.uk/

More information

Lecture 4: Higher Order Functions

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

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

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction. Practical Practical An introduction to functional programming July 21, 2011 Contents Practical Practical is fun, and that s what it s all about! Even if seems strange to you at first, don t give up. Learning

More information

Induction in Coq. Nate Foster Spring 2018

Induction in Coq. Nate Foster Spring 2018 Induction in Coq Nate Foster Spring 2018 Review Previously in 3110: Functional programming in Coq Logic in Coq Curry-Howard correspondence (proofs are programs) Today: Induction in Coq REVIEW: INDUCTION

More information

02157 Functional Programming. Michael R. Ha. Sequences and Sequence Expressions. Michael R. Hansen

02157 Functional Programming. Michael R. Ha. Sequences and Sequence Expressions. Michael R. Hansen Sequences and Sequence Expressions nsen 1 DTU Compute, Technical University of Denmark Sequences and Sequence Expressions MRH 14/11/2018 Sequence: a possibly infinite, ordered collection of elements, where

More information

Option Values, Arrays, Sequences, and Lazy Evaluation

Option Values, Arrays, Sequences, and Lazy Evaluation Option Values, Arrays, Sequences, and Lazy Evaluation Björn Lisper School of Innovation, Design, and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ Option Values, Arrays,

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

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

Recursion. Tjark Weber. Functional Programming 1. Based on notes by Sven-Olof Nyström. Tjark Weber (UU) Recursion 1 / 37

Recursion. Tjark Weber. Functional Programming 1. Based on notes by Sven-Olof Nyström. Tjark Weber (UU) Recursion 1 / 37 Tjark Weber Functional Programming 1 Based on notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 37 Background FP I / Advanced FP FP I / Advanced FP This course (Functional Programming I) (5 hp,

More information

Fall 2018 Lecture 7. Stephen Brookes

Fall 2018 Lecture 7. Stephen Brookes 15-150 Fall 2018 Lecture 7 Stephen Brookes last time Sorting a list of integers Specifications and proofs helper functions that really help principles Every function needs a spec Every spec needs a proof

More information

More fun with recursion

More fun with recursion Informatics 1 Functional Programming Lecture 6 More fun with recursion Don Sannella University of Edinburgh Part I Counting Counting Prelude [1..3] [1,2,3] Prelude enumfromto 1 3 [1,2,3] [m..n] stands

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

Recap: ML s Holy Trinity

Recap: ML s Holy Trinity Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression 2. ML checks if expression is well-typed Using a precise set

More information

CSE 341 Sample Midterm #2

CSE 341 Sample Midterm #2 1. s For each ML expression in the left-hand column of the table below, indicate in the right-hand column its value. Be sure to (e.g., 7.0 rather than 7 for a real; Strings in quotes e.g. "hello"; true

More information

Homework 3 COSE212, Fall 2018

Homework 3 COSE212, Fall 2018 Homework 3 COSE212, Fall 2018 Hakjoo Oh Due: 10/28, 24:00 Problem 1 (100pts) Let us design and implement a programming language called ML. ML is a small yet Turing-complete functional language that supports

More information

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

More information

GADTs. Wouter Swierstra. Advanced functional programming - Lecture 7. Faculty of Science Information and Computing Sciences

GADTs. Wouter Swierstra. Advanced functional programming - Lecture 7. Faculty of Science Information and Computing Sciences GADTs Advanced functional programming - Lecture 7 Wouter Swierstra 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree a) This definition introduces:

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

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

An introduction to functional programming. July 23, 2010

An introduction to functional programming. July 23, 2010 An introduction to functional programming July 23, 2010 About Outline About About What is functional programming? What is? Why functional programming? Why? is novel. is powerful. is fun. About A brief

More information

36 Modular Arithmetic

36 Modular Arithmetic 36 Modular Arithmetic Tom Lewis Fall Term 2010 Tom Lewis () 36 Modular Arithmetic Fall Term 2010 1 / 10 Outline 1 The set Z n 2 Addition and multiplication 3 Modular additive inverse 4 Modular multiplicative

More information

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

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

More information

Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca

Lists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca Lists Adrian Groza Department of Computer Science Technical University of Cluj-Napoca Recall... Parameter evaluation Call-by-value Call-by-name Call-by-need Functions Infix operators Local declarations,

More information

Problem Set CVO 103, Spring 2018

Problem Set CVO 103, Spring 2018 Problem Set CVO 103, Spring 2018 Hakjoo Oh Due: 06/12 (in class) Problem 1 The Fibonacci numbers can be defined as follows: 0 if n = 0 fib(n) = 1 if n = 1 fib(n 1) + fib(n 2) otherwise Write in OCaml the

More information

15 150: Principles of Functional Programming Sorting Integer Lists

15 150: Principles of Functional Programming Sorting Integer Lists 15 150: Principles of Functional Programming Sorting Integer Lists Michael Erdmann Spring 2018 1 Background Let s define what we mean for a list of integers to be sorted, by reference to datatypes and

More information

Programming Languages Fall 2013

Programming Languages Fall 2013 Programming Languages Fall 2013 Lecture 2: types Prof. Liang Huang huang@qc.cs.cuny.edu Recap of Lecture 1 functional programming vs. imperative programming basic Haskell syntax function definition lazy

More information

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

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

More information

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

CSE 130 Programming Languages. Datatypes. Ranjit Jhala UC San Diego CSE 130 Programming Languages Datatypes Ranjit Jhala UC San Diego Recap: ML s Holy Trinity Expressions (Syntax) Exec-time Dynamic Values (Semantics) Compile-time Static Types 1. Programmer enters expression

More information

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group Advanced Type System Features Tom Schrijvers Leuven Haskell User Group Data Recursion Genericity Schemes Expression Problem Monads GADTs DSLs Type Type Families Classes Lists and Effect Free Other Handlers

More information

CS 320: Concepts of Programming Languages

CS 320: Concepts of Programming Languages CS 320: Concepts of Programming Languages Wayne Snyder Computer Science Department Boston University Lecture 04: Basic Haskell Continued o Polymorphic Types o Type Inference with Polymorphism o Standard

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

GADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]

GADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences] GADTs AFP Summer School Alejandro Serrano 1 Today s lecture Generalized algebraic data types (GADTs) 2 A datatype data Tree a = Leaf Node (Tree a) a (Tree a) This definition introduces: 3 A datatype data

More information

CS 340 Spring 2019 Midterm Exam

CS 340 Spring 2019 Midterm Exam CS 340 Spring 2019 Midterm Exam Instructions: This exam is closed-book, closed-notes. Electronic devices of any kind are not permitted. Write your final answers, tidily, in the boxes provided. Scratch

More information

The Worker/Wrapper Transformation

The Worker/Wrapper Transformation The Worker/Wrapper Transformation Andy Gill 1 Graham Hutton 2 1 Galois, Inc. 2 University of Nottingham February 6, 2008 Andy Gill, Graham Hutton The Worker/Wrapper Transformation February 6, 2008 1 /

More information

Chapter 3 Programming with Recursion

Chapter 3 Programming with Recursion Plan Chapter 3 Programming with Recursion 1. Examples... 3.2 2. Correctness... 3.5 3. Construction methodology... 3.13 4. Forms of recursion... 3.16 Sven-Olof Nyström/IT Dept/Uppsala University FP 3.1

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

CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Christian Collberg collberg+372@gmail.com Department of Computer Science University of Arizona Copyright c 2005 Christian Collberg

More information

COS 326 David Walker Princeton University

COS 326 David Walker Princeton University Functional Abstractions over Imperative Infrastructure and Lazy Evaluation COS 326 David Walker Princeton University slides copyright 2013-2015 David Walker and Andrew W. Appel permission granted to reuse

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

6.037 Lecture 7B. Scheme Variants Normal Order Lazy Evaluation Streams

6.037 Lecture 7B. Scheme Variants Normal Order Lazy Evaluation Streams 6.037 Lecture 7B Scheme Variants Normal Order Lazy Evaluation Streams Edited by Mike Phillips & Ben Vandiver Original Material by Eric Grimson & Duane Boning Further Variations on a Scheme Beyond Scheme

More information

Recursion. Lars-Henrik Eriksson. Functional Programming 1. Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström

Recursion. Lars-Henrik Eriksson. Functional Programming 1. Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström Lars-Henrik Eriksson Functional Programming 1 Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 41 Comparison: Imperative/Functional Programming Comparison:

More information

CSE341 Spring 2017, Midterm Examination April 28, 2017

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

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

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

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona 1/43 CSc 372 Comparative Programming Languages 8 : Haskell Function Examples Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg Functions over Lists

More information

Inductive Data Types

Inductive Data Types Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old

More information

Recursion and Induction

Recursion and Induction Recursion and Induction Paul S. Miner NASA Langley Formal Methods Group p.s.miner@nasa.gov 28 November 2007 Outline Recursive definitions in PVS Simple inductive proofs Automated proofs by induction More

More information

Fall Lecture 8 Stephen Brookes

Fall Lecture 8 Stephen Brookes 15-150 Fall 2018 Lecture 8 Stephen Brookes trees vs. lists Representing a collection as a (balanced) tree instead of a list may yield a parallel speed-up Using a sorted (balanced) tree may even yield faster

More information

Isabelle s meta-logic. p.1

Isabelle s meta-logic. p.1 Isabelle s meta-logic p.1 Basic constructs Implication = (==>) For separating premises and conclusion of theorems p.2 Basic constructs Implication = (==>) For separating premises and conclusion of theorems

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

Patterns The Essence of Functional Programming

Patterns The Essence of Functional Programming Patterns The Essence of Functional Programming Up to now we have defined functions in a very traditional way: function name + variable name parameters Read Chap 7 In functional programming we can exploit

More information

Assigning to a Variable

Assigning to a Variable What is the result of this program? Is it 0 or 1? Assigning to a Variable let f = proc(x) set x = 1 in let y = 0 in { (f y); y } 1 Assigning to a Variable let f = proc(x) set x = 1 in let y = 0 in { (f

More information

15 150: Principles of Functional Programming. Exceptions

15 150: Principles of Functional Programming. Exceptions 15 150: Principles of Functional Programming Exceptions Michael Erdmann Spring 2018 1 Topics Exceptions Referential transparency, revisited Examples to be discussed: Dealing with arithmetic errors Making

More information

Lecture 5: Lazy Evaluation and Infinite Data Structures

Lecture 5: Lazy Evaluation and Infinite Data Structures Lecture 5: Lazy Evaluation and Infinite Data Structures Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense October 3, 2017 How does Haskell evaluate a

More information

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

Recap. Recap. If-then-else expressions. If-then-else expressions. If-then-else expressions. If-then-else expressions Recap Epressions (Synta) Compile-time Static Eec-time Dynamic Types (Semantics) Recap Integers: +,-,* floats: +,-,* Booleans: =,

More information

CS 320 Midterm Exam. Fall 2018

CS 320 Midterm Exam. Fall 2018 Name: BU ID: CS 320 Midterm Exam Fall 2018 Write here the number of the problem you are skipping: You must complete 5 of the 6 problems on this exam for full credit. Each problem is of equal weight. Please

More information

15 212: Principles of Programming. Some Notes on Induction

15 212: Principles of Programming. Some Notes on Induction 5 22: Principles of Programming Some Notes on Induction Michael Erdmann Spring 20 These notes provide a brief introduction to induction for proving properties of ML programs. We assume that the reader

More information

Week 5 Tutorial Structural Induction

Week 5 Tutorial Structural Induction Department of Computer Science, Australian National University COMP2600 / COMP6260 Formal Methods in Software Engineering Semester 2, 2016 Week 5 Tutorial Structural Induction You should hand in attempts

More information

Testing. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 2. [Faculty of Science Information and Computing Sciences]

Testing. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 2. [Faculty of Science Information and Computing Sciences] Testing Advanced functional programming - Lecture 2 Wouter Swierstra and Alejandro Serrano 1 Program Correctness 2 Testing and correctness When is a program correct? 3 Testing and correctness When is a

More information

Programming Languages

Programming Languages What about more complex data? CSE 130 : Fall 2012 Programming Languages Expressions Values Lecture 3: Datatypes Ranjit Jhala UC San Diego Types Many kinds of expressions: 1. Simple 2. Variables 3. Functions

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

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

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1 A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns

More information

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza Haskell 101 (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza Haskell 101: Contents Introduction Tutorial Homework Bibliography Haskell 101: Contents Introduction Tutorial Homework Bibliography Haskell

More information

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

Programming Languages

Programming Languages CSE 130 : Fall 2008 Programming Languages Lecture 6: Datatypes t and Recursion Ranjit Jhala UC San Diego News PA 2 Due Fri (and PA3 up) PA3 is a bit difficult, but do it yourself, or repent in the final

More information

Declaring Numbers. Bernd Braßel, Frank Huch and Sebastian Fischer. Department of Computer Science, University of Kiel, Germany

Declaring Numbers. Bernd Braßel, Frank Huch and Sebastian Fischer. Department of Computer Science, University of Kiel, Germany Declaring Numbers Bernd Braßel, Frank Huch and Sebastian Fischer Department of Computer Science, University of Kiel, Germany WFLP 2007, Paris, France I m going to present joint work with my colleagues

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

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