Call-by-name evaluation

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

Fall 2018 Lecture N

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

ITERATORS AND STREAMS 9

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Option Values, Arrays, Sequences, and Lazy Evaluation

F28PL1 Programming Languages. Lecture 14: Standard ML 4

Lists. Michael P. Fourman. February 2, 2010

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

About coding style Spring February 9, 2004

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

Supplementary Notes on Concurrent ML

15 212: Principles of Programming. Some Notes on Continuations

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

Homework 3 COSE212, Fall 2018

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

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

Sometimes it s good to be lazy

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

Plan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually

Functional Programming and Haskell

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

ML Type Inference and Unification. Arlen Cox

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

Logic - CM0845 Introduction to Haskell

Lazy Evaluation in Scala

Programming Languages

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

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

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

A list is a finite sequence of elements. Elements may appear more than once

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Programming Languages

15 210: Parallel and Sequential Data Structures and Algorithms

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

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

CSE 341 Sample Midterm #2

Programming Languages

SML A F unctional Functional Language Language Lecture 19

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

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

Programming Languages

Principles of Programming Languages 2013 Practical Session 01 ML and Lazy Lists

CITS3211 FUNCTIONAL PROGRAMMING. 7. Lazy evaluation and infinite lists

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

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

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

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

CSE341, Fall 2011, Midterm Examination October 31, 2011

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

Recap: ML s Holy Trinity

Programming Languages

CS 320: Concepts of Programming Languages

"Object Oriented" Programming using ML

CS 320: Concepts of Programming Languages

max function Next concat function max function What s the pattern? concat function More on recursion Higher-order functions

CS558 Programming Languages

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.

A Brief Introduction to Standard ML

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Data Types The ML Type System

Lambda Calculus as a Programming Language

Currying fun f x y = expression;

Higher-Order Functions

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

CS32 - Week 2. Umut Oztok. July 1, Umut Oztok CS32 - Week 2

CSE341, Fall 2011, Midterm Examination October 31, 2011

COMPUTER SCIENCE TRIPOS

Chapter 3 Linear Structures: Lists

Overview. CS301 Session 3. Problem set 1. Thinking recursively

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

Computer Science 312 Fall Prelim 2 SOLUTIONS April 18, 2006

CS558 Programming Languages

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

CSC/MAT-220: Lab 6. Due: 11/26/2018

Functional Programming

Lambda Calculus as a Programming Language

Streams and Evalutation Strategies

UNIVERSITY OF EDINBURGH COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS

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

CSE 341 Section 5. Winter 2018

CSE-321 Programming Languages 2010 Midterm

Combining Programming with Theorem Proving

Programming in Standard ML: Continued

Fall Lecture 3 September 4. Stephen Brookes

A Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1

COS 326 David Walker Princeton University

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

Introduction to Functional Programming

CSE341 Spring 2016, Final Examination June 6, 2016

Chapter 15. Functional Programming Languages

Name: Entry: Gp: 1. CSL 102: Introduction to Computer Science. Minor 2 Mon 21 Mar 2005 VI 301(Gps 1-6)& VI 401(Gps 7-8) 9:30-10:30 Max Marks 40

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

Lectures 24 and 25: Scheduling; Introduction to Effects

Lecture 19: Signatures, Structures, and Type Abstraction

CSE 341 : Programming Languages Midterm, Spring 2015

Structure and Interpretation of Computer Programs

61A Lecture 32. Wednesday, November 14

Mutation. COS 326 David Walker Princeton University

Some Advanced ML Features

Transcription:

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. References: [MLWP, Chapter 5] Call-by-name evaluation To compute the value of F(E), first compute the value of the expression F to obta a function value, say f. Then compute the value of the expression obtaed by substitutg the expression E for the formal parameter of the function f to its body. NB: Call-by-need is similar, but duplicated expressions are only evaluated once. (Haskell is the most widely used call-by-need purely-functional programmg language.) / 1 / 2 Example: Consider the followg function defitions. fun pred n = if n = 0 then [] else n :: pred(n-1) ; fun lsum( [], l ) = 0 lsum( h::t, l ) = h + lsum( t, l ) ; val pred = fn : t -> t list val lsum = fn : t list * a -> t 1. Call-by-value evaluation. lsum( pred(2), pred(10000) ) pred(2) 2::pred(1) 2::1::pred(0) 2::1::[] pred(10000) 10000::pred(9999) 10000::9999::...1::[] lsum( 2::1::[], 10000::9999...1::[] ) 2 + lsum( 1::[], 10000::9999...1::[] ) 2 + ( 1 + lsum( [], 10000::9999...1::[] ) ) 2 + ( 1 + 0 ) 2 + 1 3 / 3 / 4

2. Call-by-name evaluation. lsum( pred(2), pred(10000) ) pred(2) 2::pred(2-1) 2 + lsum( pred(2-1), pred(10000) ) pred(2-1) 1::pred(1-1) 2 + ( 1 + lsum( pred(1-1), pred(10000) ) ) pred(1-1) [] 2 + ( 1 + 0 ) 2 + 1 3 Lazy datatypes Lazy datatypes are one of the most celebrated features of functional programmg. The elements of a lazy datatype are not evaluated until their values are required. Thus a lazy datatype may have fite values, of which we may view any fite part but never the whole. In a call-by-value functional language, like ML, we implement lazy datatypes by explicitly delayg evaluation. Indeed, to delay the evaluation of an expression E, we can use the nameless function fn() => E stead, and we force the evaluation of this expression by the function application (fn() => E)(). / 5 / 6 Examples: 1. Sequences (= fite and fite lists). datatype a seq = nil cons of a * ( unit -> a seq ) ; 2. Streams (= fite lists). datatype a stream = cons of unit -> a * a stream ; 3. Fite and fite non-empty fitely-branchg trees. datatype a ffbtree = W of a * (unit -> a ffbtree list) ; Lazy evaluation ML Example: Consider the followg function defitions ML. fun seqpred n = if n = 0 then nil else cons( n, fn() => seqpred(n-1) ) ; fun seqlsum( nil, l ) = 0 seqlsum( cons(h,t), l ) = h + seqlsum( t(), l ) ; val seqpred = fn : t -> t seq val seqlsum = fn : t seq * a -> t! Evaluate seqlsum( seqpred(2), seqpred(10000) ) and compare the process with the call-by-name evaluation of lsum( pred(2), pred(10000) )! / 7 / 8

Sequence manipulation datatype a seq = nil cons of a * ( unit -> a seq ) ; 1. Head, tail, and null testg. exception Empty ; fun seqhd nil = raise Empty seqhd( cons(h,t) ) = h ; fun seqtl nil = raise Empty seqtl( cons(h,t) ) = t() ; fun seqnull nil = true seqnull _ = false ; val seqhd = fn : a seq -> a val seqtl = fn : a seq -> a seq val seqnull = fn : a seq -> bool 2. Constant sequences. fun Kseq x = cons( x, fn() => Kseq x ) ; val Kseq = fn : a -> a seq 3. Traces. fun trace f s = case s of NONE => nil SOME x => cons( x, fn() => trace f (f x) ) ; fun from n = trace (fn x => SOME(x+1)) (SOME n) ; val trace = fn : ( a -> a option) -> a option -> a seq val from = fn : t -> t seq / 9 / 10 4. Sequence display. exception Negative ; fun display n s = if n < 0 then raise Negative else if n = 0 then [] else (seqhd s) :: display (n-1) (seqtl s) ; val display = fn : t -> a seq -> a list 5. Append and shuffle. fun seqappend( nil, s ) = s seqappend( s, t ) = cons( seqhd s, fn() => seqappend( seqtl s, t ) ) ; val seqappend = fn : a seq * a seq -> a seq fun shuffle( nil, s ) = s shuffle( s, t ) = cons( seqhd s, fn () => shuffle( t, seqtl s ) ) ; val shuffle = fn : a seq * a seq -> a seq 6. Functionals: filter, map, fold. fun seqfilter P nil = nil seqfilter P s val h = seqhd s if P h then cons( h, fn() => seqfilter P (seqtl s) ) else seqfilter P (seqtl s) val seqfilter = fn : ( a -> bool) -> a seq -> a seq / 11 / 12

fun seqmap f nil = nil seqmap f s = cons( f( seqhd s ), fn() => seqmap f (seqtl s) ) ; val seqmap = fn : ( a -> b) -> a seq -> b seq fun seqnfold n f x s = if n < 0 then raise Negative else if n = 0 then x else if seqnull s then raise Empty else seqnfold (n-1) f ( f(seqhd s,x) ) (seqtl s) ; val seqnfold = fn : t -> ( a * b -> b) -> b -> a seq -> b Generatg the prime numbers Streams datatype a stream = cons of unit -> a * a stream ; fun head (cons f) val (h,_) = f() h fun tail (cons f) val (_,t) = f() t val head = fn : a stream -> a val tail = fn : a stream -> a stream / 13 / 14 fun filter P s fun auxfilter s val h = head s if P h then cons( fn() => ( h, auxfilter(tail s) ) ) else auxfilter( tail s ) end auxfilter s val filter = fn : ( a -> bool) -> a stream -> a stream Sieve of Eratosthenes (I) fun sieve s val h = head s val sift = filter (fn n => n mod h <> 0) ; cons( fn() => ( h, sieve( sift (tail s) ) ) ) val sieve = fn : t stream -> t stream fun from n = cons( fn () => ( n, from(n+1) ) ) ; val primes = sieve( from 2 ) ; val from = fn : t -> t stream val primes = cons fn : t stream / 15 / 16

Sieve of Eratosthenes (II) fun sieve s = case head s of NONE => cons( fn() => ( NONE, sieve( tail s ) ) ) SOME h => let fun sweep s = itsweep s 1 and itsweep s n = cons( fn() => if n = h then ( NONE, sweep (tail s) ) else ( head s, itsweep (tail s) (n+1) ) ) cons( fn() => ( SOME h, sieve( sweep (tail s) ) ) ) Infite-tree manipulation datatype a ffbtree = W of a * ( unit -> a ffbtree list ) ; 1. Computation trees. fun CT f s = W( s, fn() => map (CT f) (f s) ) ; val CT = fn : ( a -> a list) -> a -> a ffbtree val sieve = fn : t option stream -> t option stream / 17 / 18 2. Breadth-first traversal. fun BFseq [] = nil BFseq( W(x,F):: T ) = cons( x, fn() => BFseq( T @ F() ) ) ; val BFseq = fn : a ffbtree list -> a seq 3. Depth-first traversal. fun DFseq [] = nil DFseq( W(x,F)::T ) = cons( x, fn() => DFseq( F() @ T ) ) ; val DFseq = fn : a ffbtree list -> a seq / 19