CS 312 11 April 2002 Lazy Evaluation, Thunks, and Streams.

Slides:



Advertisements
Similar presentations
More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Advertisements

Closures & Environments CS153: Compilers Greg Morrisett.
Type Checking, Inference, & Elaboration CS153: Compilers Greg Morrisett.
Assignments and Procs w/Params EOPL3 Chapter 4. Expressible vs. Denotable values Expressible Values –the language can express and compute these –represented.
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
Recap 1.Programmer enters expression 2.ML checks if expression is “well-typed” Using a precise set of rules, ML tries to find a unique type for the expression.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
CSE341: Programming Languages Lecture 12 Equivalence Dan Grossman Spring 2013.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Fall 2011.
CSE341: Programming Languages Lecture 15 Mutation, Pairs, Thunks, Laziness, Streams, Memoization Dan Grossman Fall 2011.
1 CS 312 – Lecture 28 Continuations –Probably the most confusing thing you’ve seen all semester… Course summary –Life after CS 312.
6.001 SICP 1 Normal (Lazy) Order Evaluation Memoization Streams.
CS 312 Spring 2004 Lecture 18 Environment Model. Substitution Model Represents computation as doing substitutions for bound variables at reduction of.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Chapter 15 Other Functional Languages. Copyright © 2007 Addison-Wesley. All rights reserved. Functional Languages Scheme and LISP have a simple syntax.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
CS 312 Spring 2002 Lecture 16 The Environment Model.
Chapter 15 Functional Programming Languages. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Design of imperative languages is.
Cs776 (Prasad)L15strm1 Reasoning with Functional Programs Optimization by source to source transformation Well-founded induction Streams : Infinite lists.
1 SML fn x => e e 1 e 2 0, 1, 2,..., +, -,... true, false, if e then e else e patterns datatypes exceptions structures functors fun f x = e variables.
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
Formal Semantics Chapter Twenty-ThreeModern Programming Languages, 2nd ed.1.
1 ML fun x -> e e 1 e 2 0, 1, 2,..., +, -,... true, false, if e then e else e patterns datatypes exceptions structures functors let f x = e variables These.
Lecture 31: Laziness University of Virginia cs1120 Fall 2009 David Evans.
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
-Calculus Kangwon National University 임현승 Programming Languages These slides are based on the slides by Prof. Sungwoo Park at POSTECH.
Advanced Functional Programming Tim Sheard 1 Lecture 17 Advanced Functional Programming Tim Sheard Oregon Graduate Institute of Science & Technology Lecture:
Today’s Agenda ML Development Workflow –Emacs –Using use –The REPL More ML –Shadowing Variables –Debugging Tips –Boolean Operations –Comparison Operations.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
© Kenneth C. Louden, Chapter 7 - Control I: Expressions and Statements Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
CSE 341 Lecture 21 delayed evaluation; thunks; streams slides created by Marty Stepp
CS314 – Section 5 Recitation 9
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2017.
6.001 SICP Variations on a Scheme
CS 3304 Comparative Languages
More on Lambda Calculus
CS 611: Lecture 9 More Lambda Calculus: Recursion, Scope, and Substitution September 17, 1999 Cornell University Computer Science Department Andrew Myers.
CS4450: Principles of Programming Languages
Functional Programming Lecture 2 - Functions
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Winter 2013.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Zach Tatlock Winter 2018.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2013.
CSE 341: Programming Langs
Streams Sections 3.5.1,3.5.2 Pages
FP Foundations, Scheme In Text: Chapter 14.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2016.
CSE341: Programming Languages Lecture 12 Equivalence
Dynamic Scoping Lazy Evaluation
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Autumn 2017.
CSE341: Programming Languages Lecture 12 Equivalence
CSE341: Programming Languages Lecture 12 Equivalence
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Autumn 2018.
6.001 SICP Streams – the lazy way
Lecture 27: In Praise of Idleness CS200: Computer Science
6.001 SICP Further Variations on a Scheme
Streams, Delayed Evaluation and a Normal Order Interpreter
6.001 SICP Variations on a Scheme
Dan Grossman / Eric Mullen Autumn 2017
CSE341: Programming Languages Lecture 12 Equivalence
Assignments and Procs w/Params
Functional Programming Lecture 2 - Functions
CSE341: Programming Languages Lecture 12 Equivalence
CSE341: Programming Languages Lecture 12 Equivalence
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2019.
Presentation transcript:

CS April 2002 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 condition expression to true or false, lazily evaluates e 1, e 2 fn (x) => e is a value Function bodies are lazily evaluated.

Factorial – right and wrong fun factorial (n : int) : int = if n <= 0 then 1 else n*factorial(n-1) When evaluating factorial 0, when do we evaluate n*factorial(n-1)? fun factorial2 (n : int) : int = my_if(n <= 0, 1, n*factorial(n-1)) When evaluating factorial2 0, when do we evaluate n*factorial(n-1)?

Eager evaluation in ML Function arguments are evaluated before the function is called (and the values are passed) One if-branch is evaluated after the guard is evaluated Function bodies are not evaluated until the function is applied. We need some laziness to make things work…

Laziness and redundancy Eager language (SML) let x = v in e 2  e 2 { v / x } (fn(x) => e 2 ) (v)  e 2 { v / x } –Bound value is evaluated eagerly before body e 2 Lazy language: let x = e 1 in e 2  e 2 { e 1 / x } (fn(x) => e 2 ) (e 1 )  e 2 { e 1 / x } –e 1 is not evaluated until x is used –Variable can stand for unevaluated expression –Problem: what if x occurs 10 times in e 2

A funny rule val f = fn()=>e evaluates e every time but not until f is called. val f = e evaluates e once “right away”. What if we had val f = Thunk.make (fn()=> e) which evaluates e once, but not until we use f. This is called “lazy evaluation”

Lazy Evaluation val f = Thunk.make (fn()=> e) which evaluates e once, but not until we use f Best of both worlds: no redundant evaluations, no unnecessary evaluations But…harder to reason about when something happens (but maybe you don’t care!) How to make sure we evaluate e at most once?

The Thunk ADT signature THUNK = sig (* A ‘a thunk is a lazily * evaluated expression e of type * ‘a. *) type 'a thunk (* make(fn()=>e) creates a thunk * for e *) val make : (unit->'a) -> 'a thunk (* apply(t) is the value of its * expression, which is only evaluated * once. *) apply : 'a thunk -> 'a end

Lazy languages Implementation has to use a ref. (How else could Thunk.apply e act differently at different times?) Some languages have special syntax for lazy evaluation. Algol-60, Haskell, Miranda: val x = e acts like val x = Thunk.make (fn()=> e) We implemented lazy evaluation using refs and functions – lazy functional languages have this implementation baked in.

Streams A stream is an “infinite” list – you can ask for the rest of it as many times as you like and you’ll never get null. The universe is finite, so a stream must really be an object that acts like an infinite list. The idea: use a function to describe what comes next.

The Stream ADT signature STREAM = sig type 'a stream val make: ('a*('a->'a)) -> 'a stream val next: 'a stream -> ('a*'a stream) end; Example: infinite list of primes

That was cool… We could model infinite sequences (of numbers, of circuit states, of whatever) without destroying old versions with refs. In fact, the stream is non-imperative! (if function is non-imperative) State without the side effects

Implementing streams (wrong) Intuitively: datatype 'a stream = Cons of ('a * 'a stream) fun make (init:'a, f:'a -> 'a): 'a stream = Cons(init, make (f init, f)) fun next (Str(th):'a stream): 'a*'a stream = th But what is make going to do?

The Punch-line If only there were a way to delay the making of the rest of the stream until the previous items had been accessed… 01 fn () => … … (See stream.sml for a correct implementation.)

Comments The streams client can tell if we’re memoizing or not. We can also implement streams with hidden “state” (see streams2.sml)

Summary ADTs for lazy computation: Thunk – one lazy expression Stream – infinite sequence, lazily computed MiniML objects: fields eagerly evaluated, can’t mention “this”. Lazy language: can mention this even in fields: new T { ones = 1::ones } Look over this stuff in a quiet room.