Cs7100(Prasad)L11Clos1 Closures and Streams. Contemporary Interest in Closures The concept of closures was developed in the 1960s and was first fully.

Slides:



Advertisements
Similar presentations
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 5. 2 List Utilities Scheme built-in procedures –(list x y z...) –(list-ref lst index) –(length lst) –(append.
Advertisements

1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
1 Programming Languages (CS 550) Lecture 7 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts used in EMF. Read.
מבוא מורחב - שיעור 91 Lecture 9 Lists continued: Map, Filter, Accumulate, Lists as interfaces.
מבוא מורחב - שיעור 15 1 Lecture 15 Streams. מבוא מורחב - שיעור 15 2 Streams: Motivation (define (sum-primes a b) (define (iter count accum) (cond ((>
6.001 SICP 1 Normal (Lazy) Order Evaluation Memoization Streams.
Chapter 15 Other Functional Languages. Copyright © 2007 Addison-Wesley. All rights reserved. Functional Languages Scheme and LISP have a simple syntax.
Chapter 15 Functional Programming Languages. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Design of imperative languages is.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 13. Streams 3.5, pages definitions file on web 2.
SICP Infinite streams – using lazy evaluation Beyond Scheme – designing language variants: Streams – an alternative programming style!
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Cs776 (Prasad)L15strm1 Reasoning with Functional Programs Optimization by source to source transformation Well-founded induction Streams : Infinite lists.
Closures and Streams More on Evaluations CS784(pm)1.
1 Lecture OO, the notion of inheritance 3 Stacks in OO style (define (make-stack) (let ((top-ptr '())) (define (empty?) (null? top-ptr)) (define.
CS 152: Programming Language Paradigms February 24 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
CS220 Programming Principles 프로그래밍의 이해 2002 가을학기 Class 13: Streams 한 태숙.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
1 Append: process  (append list1 list2) (cons 1 (append ‘(2) list2)) (cons 1 (cons 2 (append ‘() list2))) (cons 1 (cons 2 list2)) (define (append list1.
Practice session #6: 1. Sequence operations 2. Partial evaluation with currying 3. Lazy-lists.
Comparative Programming Languages Language Comparison: Scheme, Smalltalk, Python, Ruby, Perl, Prolog, ML, C++/STL, Java, Haskell.
ISBN Chapter 15 Functional Programming Languages.
1 Programming Languages (CS 550) Lecture 4 Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
PPL Lazy Lists. Midterm 2012 (define sum-vals (λ (ts) (if (ts-simple? ts) (ts-val ts) (accumulate + 0 (map ts-val (ts-inner-slots ts))))))
From Lambda Calculus to LISP Functional Programming Academic Year Alessandro Cimatti
1 מבוא מורחב למדעי המחשב בשפת Scheme תרגול Outline Mutable list structure RPN calculator Vectors and sorting.
Cs3180 (Prasad)L156HOF1 Higher-Order Functions. cs3180 (Prasad)L156HOF2 Equivalent Notations (define (f x y) (… body …)) = (define f (lambda (x y) (…
Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency.
6.037 Lecture 7B Scheme Variants Normal Order Lazy Evaluation Streams Edited by Mike Phillips & Ben Vandiver Original Material by Eric Grimson & Duane.
Functional Programming
CS314 – Section 5 Recitation 10
Additional Scheme examples
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2017.
Lecture 16 Streams continue Infinite Streams מבוא מורחב - שיעור 16.
6.001 SICP Variations on a Scheme
PPL Lecture Notes: Chapter 3 High-Order Procedures Revisited.
PPL Lazy Lists.
(defmacro (delay x) (list 'lambda () x))
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Winter 2013.
Closures and Streams cs784(Prasad) L11Clos
COP4020 Programming Languages
Env. Model Implementation
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.
Streams Sections 3.5.1,3.5.2 Pages
The Metacircular Evaluator
Lecture 18 Infinite Streams and
FP Foundations, Scheme In Text: Chapter 14.
PPL Sequence Interface.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Spring 2016.
Lecture 18.
Dynamic Scoping Lazy Evaluation
The Metacircular Evaluator
Lecture #8 מבוא מורחב.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Autumn 2017.
CSE341: Programming Languages Lecture 14 Thunks, Laziness, Streams, Memoization Dan Grossman Autumn 2018.
6.001 SICP Streams – the lazy way
6.001 SICP Further Variations on a Scheme
Streams, Delayed Evaluation and a Normal Order Interpreter
List and list operations (continue).
Closures and Streams cs7100(Prasad) L11Clos
6.001 SICP Interpretation Parts of an interpreter
Lecture # , , , , מבוא מורחב.
Rehearsal: Lazy Evaluation Infinite Streams in our lazy evaluator
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:

cs7100(Prasad)L11Clos1 Closures and Streams

Contemporary Interest in Closures The concept of closures was developed in the 1960s and was first fully implemented in 1975 as a language feature in the Scheme programming language to support lexically scoped first-class functions. Project Lambda makes it easier to write code for multi- core processors by adding closures to the Java language and extending the Java API to support parallelizable operations upon streamed data. Rick Hickey’s Clojure (a dialect of LISP for Java platform) is a pure functional language with support for rich set of data structures, and constructs for concurrent programming. cs7100(Prasad)L11Clos2

cs7100(Prasad)L11Clos3 Models of Evaluation Substitution-based (define (square x) (* x x)) ((lambda (x y) (+ (square x) (square y))) (- 5 3) 5) =(+ (square 2) (square 5)) =(+ (* 2 2) (* 5 5)) = (+ 4 25) = 29

cs7100(Prasad)L11Clos4 Expression Evaluation Options To evaluate: (operator operand1 operand2 operand3...) Applicative-Order Evaluation ( call by value) –evaluate each of the sub-expressions. –apply the leftmost result to the rest. Normal-Order Evaluation ( call by name ) –apply the leftmost (lambda) sub-expression to the rest and expand. (Argument sub- expressions get evaluated when necessary.)

cs7100(Prasad)L11Clos5 Models of Evaluation Environment-based ((lambda (x y) (+ (square x) (square y))) (- 5 3) 5) =(+ (square x) (square y)) x=2,y=5 =(+ (* x x) x=2,y=5 x xx (* x x) ) x=5,y=5 =(+ 4 25) = 29

cs7100(Prasad)L11Clos6 An extended example (define square (lambda (x) (* x x))) (define sum-of-squares (lambda (x y) (+ (square x) (square y)))) (define f (lambda (a) (sum-of-squares (+ a 1) (* a 2))))

cs7100(Prasad)L11Clos7 Initial Global Environment

cs7100(Prasad)L11Clos8 Executing (f 5) and (sum-of-squares 6 10)

cs7100(Prasad)L11Clos9 Delayed Evaluation : THUNKS >(define x (* 5 5)) >x>x 25 >(define y (lambda () (* 5 5)) >(y) 25 Partial Evaluation : CURRYING >(define add (lambda (x) (lambda (y) (+ x y))) >(define ad4 (add 4)) >(ad4 8) 12

cs7100(Prasad)L11Clos10 Closure and Models Substitution (lambda (y) (+ 4 y) ) Substitution model is inadequate for mutable data structures. Environment < (lambda (y) (+ x y)), [x Need to distinguish location and contents of the location.

cs7100(Prasad)L11Clos11 Modular Designs with Lists

cs7100(Prasad)L11Clos12 Higher-order functions and lists Use of lists and generic higher-order functions enable abstraction and reuse –Can replace customized recursive definitions with more readable definitions built using “library” functions –The HOF approach may be less efficient. –Promotes MODULAR DESIGNS – improves programmer productivity

cs7100(Prasad)L11Clos13 (define (even-fibs n) (define (next k) (if (> k n) ’() (let ((f (fib k))) (if (even? f) (cons f (next (+ k 1))) (next (+ k 1)) )) )) (next 0)) Take a number n and construct a list of first n even Fibonacci numbers.

cs7100(Prasad)L11Clos14 Abstract Description enumerate integers from 0 to n compute the Fibonacci number for each integer filter them, selecting even ones accumulate the results using cons, starting with ()

cs7100(Prasad)L11Clos15 (define (filter pred seq) (cond ((null? seq) ’()) ((pred (car seq)) (cons (car seq) (filter pred (cdr seq)))) (else (filter pred (cdr seq))) )) (define (accumulate op init seq) (if (null? seq) init (op (car seq) (accumulate op init (cdr seq))) ))

cs7100(Prasad)L11Clos16 (define (enum-interval low high) (if (> low high) ’() (cons low (enum-interval (+ low 1) high)) )) (define (even-fibs n) (accumulate cons ’() (filter even? (map fib (enum-interval 0 n)))))

cs7100(Prasad)L11Clos17 Streams: Motivation

cs7100(Prasad)L11Clos18 Modeling real-world objects (with state) and real- world phenomena –Use computational objects with local variables and implement time variation of states using assignments –Alternatively, use sequences to model time histories of the states of the objects. Possible Implementations of Sequences –Using Lists –Using Streams Delayed evaluation (demand-based evaluation) useful (necessary) when large (infinite) sequences are considered.

cs7100(Prasad)L11Clos19 Streams : Equational Reasoning (define s (cons 0 s))  Illegal. (Solution: infinite sequence of 0’s.) … (0. (0. (0. (0. … ))))  (cf. Ada, Pascal,…) type s = record car : integer; cdr : s end;  How do we represent potentially infinite structures?

cs7100(Prasad)L11Clos20 (0.(0.(0. … ))) (0. Function which when executed generates an infinite structure ) Recursive winding and unwinding (0. ) (0.... )

cs7100(Prasad)L11Clos21 >(define stream-car car) >(define (stream-cdr s) ( ) ( (cdr s) ) ) Unwrap by executing the second. >(define stream-zeros (lambda() (cons 0 (lambda() ) stream-zeros ) ) ) Wrap by forming closure (thunk).

cs7100(Prasad)L11Clos22 >(define stream-car car) >(define (stream-cdr s) ( ) ( (cadr s) ) ) Unwrap by executing the second. >(define stream-zeros (lambda() (list 0 (lambda() ) stream-zeros ) ) ) Wrap by forming closure (thunk).

cs7100(Prasad)L11Clos23 >(stream-car (stream-cdr stream-zeros) ) >(define (numbers-from n) (cons n (lambda () (numbers-from (+ 1 n)) ))) >(define stream-numbers (numbers-from 0) )

cs7100(Prasad)L11Clos24 (define stream-car car) (define (stream-cdr s) () ( (cdr s) ) ) (define (stream-cons x s) ( lambda ( )) (cons x ( lambda ( ) s) ) ) (define the-empty-stream ’() ) (define stream-null? null?) Recapitulating Stream Primitives

cs7100(Prasad)L11Clos25 (define (stream-filter p s) (cond ((stream-null? s) the-empty-stream) ((p (stream-car s)) (stream-cons (stream-car s) (stream-filter p (stream-cdr s)))) (else (stream-filter p (stream-cdr s))) )) (define (stream-enum-interval low high) (if (> low high) the-empty-stream (stream-cons low (stream-enum-interval (+ 1 low) high))))

cs7100(Prasad)L11Clos26 (stream-car (stream-cdr (stream-filter prime? (stream-enum-interval )))) (define (fibgen f1 f2) (cons f1 (lambda () (fibgen f2 (+ f1 f2))) )) (define fibs (fibgen 0 1))

cs7100(Prasad)L11Clos27 Factorial Revisited (define (trfac n) (letrec ( (iter (lambda (i a) (if (zero? i) a (iter (- i 1) (* a i))))) ) (iter n 1) )

cs7100(Prasad)L11Clos28 (define (ifac n) (let (( i n ) ( a 1 )) (letrec ( (iter (lambda () (if (zero? i) a (begin (set! a (* a i)) (set! i (- i 1)) (iter) )) ) (iter) ) ))

cs7100(Prasad)L11Clos29 Factorial Stream (define (str n r) (cons r (lambda () (str (+ n 1) (* n r)) ) ) ) (define sfac (str 1 1)) (car ((cdr ((cdr ((cdr sfac)) )) )) ) … (stream-cdr … ) Demand driven generation of list elements. Caching/Memoing necessary for efficiency. Avoids assignment.