Principles of Programming Languages

Size: px
Start display at page:

Download "Principles of Programming Languages"

Transcription

1 Principles of Programming Languages Slides by Yaron Gonen and Dana Fisman Based on Book by Mira Balaban and Lesson 20 Lazy Lists Collaboration and Management Dana Fisman 1

2 Lazy Lists

3 Lazy Lists We have seen Generators in TypeScript They are founded on the idea of Lazy Lists A Lazy List is a smart data structure for holding lists It is useful for holding infinite lists or very long lists

4 Motivation Suppose we want to compute the first prime between 1,000 to 1,000,000 (car (filter prime? (enumerate_interval ))) We ll have to store and process this very long list

5 Lazy Lists How can we hold a list in a compact way? If we have an arbitrary long/inf list of elements, there is no way to represent it compactly. Luckily, the long/inf list we are usually interested in have some structure In particular, it is possible to compute the next element in the list.

6 Lazy Lists the idea Given that we have a way to compute the next element All we need to store is: The first element What params should rest() receive? The function to compute the next element, or more accurately, the rest of the list. Basically, document the inductive definition of the list Again, we are using the principle of delayed computation

7 Lazy Lists Type Homogeneous lazy list: LzL(T) = empty-lzl T * [Empty -> LzL(T)] Heterogeneous lazy list: First Element Rest-of-List func. LzL = empty-lzl T * [Empty -> LzL] First Element Rest-of-List func.

8 Lazy Lists Artificial Example (define L0 '()) (define L1 (cons 1 (λ () L0))) (define L2 (cons 2 (λ () L1))) > L0 '() > L1 '(1. #<procedure>) > ((cdr L1)) '() > L2 '(2. #<procedure>) > ((cdr L2)) '(1. #<procedure>)

9 Lazy Lists Integers Example Define a procedure that Given an integer n Returns a lazy list of all integers m s.t. m >= n (define integers-from (λ (n) (cons n (λ () (integers-from (add1 n)))))) Lazy list

10 Lazy Lists Integers Example Define a procedure that Given an integer n Returns a lazy list of all integers m s.t. m >= n (define integers-from (λ (n) (cons n (λ () (integers-from (add1 n)))))) first element rest-of-list func. Lazy list

11 Lazy Lists Integers Example Define a procedure that Given an integer n Returns a lazy list of all integers m s.t. m >= n (define integers-from (λ (n) (cons n (λ () (integers-from (add1 n)))))) > (integers-from 17) '(17. #<procedure>) > ((cdr (integers-from 17))) '(18. #<procedure>)

12 Lazy Lists - ADT Let s see what is the interface we d like for our lazy lists. Constructors: o Constructor for empty-lzl (define empty-lzl empty) o Constructor for non-empty lzl ;; Signature: cons-lzl(x,lzl) ;; Type: [T*LzL -> LzL] ;; Pre-condition: lzl is either empty-lzl or ;; <closure () Lazy-list> (define cons-lzl cons)

13 Lazy Lists - ADT Selectors: o First Element ;; Signature: head(lz-ist) ;; Type: [LzL -> T] ;; that is, the type is [T * [Empty->LzL] -> T] ;; Pre-condition: lzl-lst is not empty (define head car) o Next LzL ;; Signature: tail(lz-ist) ;; Type: [LzL -> T] ;; that is, the type is [T * [Empty->LzL] -> T] ;; Pre-condition: lzl-lst is not empty (define tail (lambda (lz-lst) ((cdr lz-lst)) ))

14 Lazy Lists Integers Example (define integers-from (λ (n) (cons n (λ () (integers-from (add1 n)))))) > (define IntFrom17 (integers-from 17)) > (head IntFrom17) 17 > (tail IntFrom17) '(18. #<procedure:...cketcode\lzl.rkt:12:12>) > (car (tail IntFrom17)) 18

15 First n Elements ;; Signature: take(lzl, n) ;; Type: [LzL(T) * Number -> List(T)] ;; or [LzL * Number -> List] if list is heterogenous ;; Purpose: return the first n elements of the list (define take (λ (lzl n) (if (= n 0) empty (cons (head lzl) (take (tail lzl) (sub1 n))))))

16 The n-th Element ;; Signature: nth(lzl, n) ;; Type: [LzL(T) * Number -> T] ;; or [LzL * Number -> Any] if list is heterogenous ;; Purpose: return the n-th element of the list ;; Precondition: lzl is not empty (define nth (λ (lzl n) (if (= n 0) (head lzl) (nth (tail lzl) (sub1 n)))))

17 range ;; Purpose: return the list of elements from m to n (define range (λ (lzl m n) (if (> m n) (error "in (range m n) n should be bigger than m") (take (list-from lzl m) (- n m))))) ;; Purpose: return the lzl starting from position k (define list-from (λ (lzl k) (cond [(= k 0) lzl] [else (list-from (tail lzl) (- k 1))])))

18 Ex: Ones Lazy List (define ones (cons 1 (lambda () ones))) >(take ones 7) `( ) > (nth ones 10) 1

19 Ex. Factorial Lazy List (define facts-from (lambda (k) (letrec ([helper (lambda (n fact-n) (cons fact-n (lambda () (helper (add1 n) (* (add1 n) fact-n)))))]) (helper k (fact k))))) (define facts-from-3 (facts-from 3)) > (take facts-from-3 6) ( )

20 Ex. Fibonnaci Lazy List (define fibs (letrec ([fibgen (lambda (a b) (cons a (lambda () (fibgen b (+ a b)))))]) (fibgen 0 1))) > (take fibs 7) ( )

21 Infinite Lists We have seen that lazy lists can hold infinite lists by capturing their inductive definition. Are there additional ways to create infinite lists? Yes, from already existing infinite lists! Let s see how we can manipulate lazy lists.

22 Applying Squares to LzL ; Type: [LzL(Num) -> LzL(Num)] (define squares-lzl (lambda (lzl) (if (empty? lzl) lzl (cons (sqr (head lzl)) (lambda () (squares-lzl (tail lzl))))))) > (take (squares-lzl ints) 7) ( )

23 Adding two LzLs (define lz-lst-add (lambda (lz1 lz2) (cond [(empty? lz1) lz2] [(empty? lz2) lz1] [else (cons (+ (head lz1) (head lz2)) (lambda () (lz-lst-add (tail lz1) (tail lz2))))])))

24 Ex. integers using addition Reminder: (define ones (cons 1 (lambda () ones))) (define integers (cons 0 (lambda () (lz-lst-add ones integers)))) > (take integers 7) ( )

25 Ex. Fibonacci using addition (define fib-numbers (cons 0 (lambda () (cons 1 (lambda () (lz-lst-add (tail fib-numbers) fib-numbers)))))) > (take fib-numbers 7) ( )

26 LzL Map (define lz-lst-map (λ (f lz) (if (empty? lz) lz (cons (f (head lz)) (λ () (lz-lst-map f (tail lz))))))) > (take (lz-lst-map (lambda (x) (* x x)) ints) 5) ( )

27 LzL Filter (define lzl-filter (λ (p? lz) (cond [(empty? lz) lz] [(p? (head lz)) (cons (head lz) (λ () (lzl-filter p? (tail lz))))] [else (lzl-filter p? (tail lz))]))) (define divisible? (λ (x y) (= (remainder x y) 0))) (define no-sevens (lzl-filter (λ (x) (not (divisible? x 7))) ints)) > (take no-sevens 15) ;The 15 th smallest integers not divisible by 7 ( ) > (nth no-sevens 100) ;The 100th integer not divisible by 7 117

28 Ex. Collatz 12 The Collatz conjecture: o Take any positive integer n. o Apply to it the following transformation: o Repeat the process indefinitely. Conjecture: no matter what number you start with, you will always eventually reach

29 Ex. Collatz 12 Collatz(n) lists: o Starting from a given number n o Define o That is The Collatz(n) list is the list of elements 8 4 a 0 a 1 a 2 a 3 2 1

30 Collatz

31 Ex. Collatz ; Signature: lzl-collatz(n) ; Type: [Number -> LzL(Number)] ; Purpose: Generate the (possibly infinite) series { n, f(n), f(f(n)),... } ; where f(n) is collatz function ; Pre-condition: n is a natural number greater than zero (define lzl-collatz (lambda (n) (if (< n 2) (cons n (lambda () empty)) (cons n (lambda () (if (= (modulo n 2) 0) (lzl-collatz (/ n 2)) (lzl-collatz (+ (* 3 n) 1)))))))) > (take (lzl-collatz 12) 10) '( ) > (take (lzl-collatz 19) 21) '( ) > (take (lzl-collatz 12) 20) car: contract violation expected: pair? given: '()

32 Ex. Collatz fix #1 ; Signature: lzl-collatz(n) ; Type: [Number -> LzL(Number)] ; Purpose: Generate the (possibly infinite) series { n, f(n), f(f(n)),... } ; where f(n) is collatz function ; Pre-condition: n is a natural number greater than zero (define lzl-collatz2 (lambda (n) (if (< n 2) ones (cons n (lambda () empty)) (cons n (lambda () (if (= (modulo n 2) 0) (lzl-collatz2 (/ n 2)) (lzl-collatz2 (+ (* 3 n) 1)))))))) > (take (lzl-collatz2 12) 10) '( ) > (take (lzl-collatz2 12) 20) '( )

33 Ex. Collatz fix #2 (define till-pred (λ (lzl p?) (cond [(empty? lzl) empty] [(pred? (head lzl)) (cons (head lzl) '())] [else (cons (head lzl) (till-pred (tail lzl) p?))]))) (define collatz-stop (lambda (x) (= x 1)))

34 Ex. Collatz > (till-pred (lzl-collatz 256) (λ (x) (= x 1))) '( ) > (till-pred (lzl-collatz 57) collatz-stop) '( ) > (length (till-pred (lzl-collatz 47) collatz-stop)) 105 > (till-pred (lzl-collatz 12) (λ (x) (= x 8))) '( ) > (till-pred (lzl-collatz 12) (λ (x) (= x 47))) '( )

35 Random LzL? We said Lazy Lists are good for structured long/inf lists. What if we want to generate a random list? ; Type: List(T) -> LzL(T) ; Purpose: Generate a lazy list whose next element is chosen ; randomly from the given list of elements (define lzl-rnd (lambda (lst) (let ([m (mth lst (random 0 (length lst)))]) (cons m (lambda () (lzl-rnd lst)))))) > (take (lzl-rnd '(1 2 3)) 10) '( ) > (take (lzl-rnd '(1 2 3)) 10) '( )

36 Back to Generators in TypeScript

37 Back to Generators in TypeScript How can we generate the same functionality with our LzL in Scheme?

38 Generators in Scheme The desired functionality: A construct that holds a lazy list To which we can apply a function next() repeatedly to the get the next element (define ints (integers-from 0)) (define squares (generator (squares-lzl ints))) > (next squares) 1 > (next squares) 4 > (next squares) 9 > (define facts (generator (facts-from 1))) > (next facts) 2 > (next facts) 6 > (next facts) 24 > (next facts) 120

39 Generators in Scheme ;; Type: LzL -> Box(LzL) (define generator (lambda (lzl) (box lzl))) ;; Type: Box(LzL(T)) -> T ; with mutation ;; Purpose: Advances the LzL of the Generator by one ;; and returns the first element of the revised LzL (define next (lambda (gen) (set-box! gen ((cdr (unbox gen)))) (car (unbox gen))))

40 Summary Lazy lists are a smart data structures that allows a compact representation of long/inf lists It uses the idea of delayed computation It is basically a pair where o the first element is a first list item and o the second element is a closure with no params specifying how to build the rest of the list Functional languages allow easy implementation of lazy lists Generators of TypeScript are founded on the idea of lazy lists

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004 Streams CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004 We ve already seen how evaluation order can change behavior when we program with state. Now we want to investigate how

More information

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

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)) SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

More information

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

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

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished

More information

Problem Set 4: Streams and Lazy Evaluation

Problem Set 4: Streams and Lazy Evaluation Due Friday, March 24 Computer Science (1)21b (Spring Term, 2017) Structure and Interpretation of Computer Programs Problem Set 4: Streams and Lazy Evaluation Reading Assignment: Chapter 3, Section 3.5.

More information

CS450 - Structure of Higher Level Languages

CS450 - Structure of Higher Level Languages Spring 2018 Streams February 24, 2018 Introduction Streams are abstract sequences. They are potentially infinite we will see that their most interesting and powerful uses come in handling infinite sequences.

More information

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 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

More About Recursive Data Types

More About Recursive Data Types More About Recursive Data Types CS 5010 Program Design Paradigms Bootcamp Lesson 5.5 Mitchell Wand, 2016-2017 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International

More information

Streams and Evalutation Strategies

Streams and Evalutation Strategies Data and Program Structure Streams and Evalutation Strategies Lecture V Ahmed Rezine Linköpings Universitet TDDA69, VT 2014 Lecture 2: Class descriptions - message passing ( define ( make-account balance

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages Lesson 14 Type Checking Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Type Checking We return to the issue of type safety we discussed informally,

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

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 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

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 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

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation? Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated

More information

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012 SCHEME COMPUTER SCIENCE 6A October 29th, 202 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, we will eventually

More information

6.001 Notes: Section 17.5

6.001 Notes: Section 17.5 6.001 Notes: Section 17.5 Slide 17.5.1 Now, let's look at one example in which changing the evaluation model allows us to explore a very different kind of computational problem. Our goal is to show how

More information

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt Data abstractions Abstractions and their variations Basic data abstractions Why data abstractions are useful Procedural abstraction Process of procedural abstraction Define formal parameters, capture process

More information

Introduction to Functional Programming

Introduction to Functional Programming Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,

More information

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016 INTERPRETERS 8 COMPUTER SCIENCE 61A November 3, 2016 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In

More information

Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))

Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1)))))) Tail Recursion 1 Tail Recursion In place of loops, in a functional language one employs recursive definitions of functions. It is often easy to write such definitions, given a problem statement. Unfortunately,

More information

ormap, andmap, and filter

ormap, andmap, and filter ormap, andmap, and filter CS 5010 Program Design Paradigms Bootcamp Lesson 6.3 Mitchell Wand, 2012-2015 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

More information

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4 CS 61A Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that

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

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses CS 6A Delayed Expressions Fall 07 Discussion 9: November 8, 07 Iterables and Iterators An iterable is any container that can be processed sequentially. Examples include lists, tuples, strings, and dictionaries.

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination

CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination COMPUTER SCIENCE 320 CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination FRIDAY, MARCH 3, 2006 Problem 1. [25 pts.] A special form is an expression that is not evaluated according to the

More information

CS115 - Module 9 - filter, map, and friends

CS115 - Module 9 - filter, map, and friends Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 19-23. Abstraction abstraction, n. 3a.... The process of isolating properties or

More information

An introduction to Scheme

An introduction to Scheme An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson Streams, Delayed Evaluation and a Normal Order Interpreter CS 550 Programming Languages Jeremy Johnson 1 Theme This lecture discusses the stream model of computation and an efficient method of implementation

More information

Streams and Lazy Evaluation in Lisp

Streams and Lazy Evaluation in Lisp Streams and Lazy Evaluation in Lisp Overview Different models of expression evaluation Lazy vs. eager evaluation Normal vs. applicative order evaluation Computing with streams in Lisp Motivation Unix Pipes

More information

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8 Question 1. (12 points) For each of the following, what value is printed? (Assume that each group of statements is executed independently in a newly reset Scheme environment.) (a) (define x 1) (define

More information

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

More information

1.3. Conditional expressions To express case distinctions like

1.3. Conditional expressions To express case distinctions like Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

More information

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters. CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

More information

Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington

Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington Programming Languages Function-Closure Idioms Adapted from Dan Grossman's PL class, U. of Washington More idioms We know the rule for lexical scope and function closures Now what is it good for A partial

More information

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams. CS 61A, Fall, 2002, Midterm #2, L. Rowe 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams. a) d) 3 1 2 3 1 2 e) b) 3 c) 1 2 3 1 2 1 2 For each of the following Scheme

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Notes on Higher Order Programming in Scheme. by Alexander Stepanov by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of

More information

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream?

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? STREAMS 10 COMPUTER SCIENCE 61AS Basics of Streams 1. What is a stream? A stream is an element and a promise to evaluate the rest of the stream. Streams are a clever idea that allows one to use sequence

More information

Scheme Basics > (butfirst '(help!)) ()

Scheme Basics > (butfirst '(help!)) () Scheme Basics > (butfirst '(help!)) () [The butfirst of a *sentence* containing one word is all but that word, i.e., the empty sentence. (BUTFIRST 'HELP!) without the inner parentheses would be butfirst

More information

CSC324 Functional Programming Efficiency Issues, Parameter Lists

CSC324 Functional Programming Efficiency Issues, Parameter Lists CSC324 Functional Programming Efficiency Issues, Parameter Lists Afsaneh Fazly 1 January 28, 2013 1 Thanks to A.Tafliovich, P.Ragde, S.McIlraith, E.Joanis, S.Stevenson, G.Penn, D.Horton 1 Example: efficiency

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

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

More information

Fall 2017 December 4, Scheme. Instructions

Fall 2017 December 4, Scheme. Instructions CS 61A Final Review Fall 2017 December 4, 2017 Instructions Form a small group. Start on the first problem. Check off with a helper or discuss your solution process with another group once everyone understands

More information

Class 6: Efficiency in Scheme

Class 6: Efficiency in Scheme Class 6: Efficiency in Scheme SI 413 - Programming Languages and Implementation Dr. Daniel S. Roche United States Naval Academy Fall 2011 Roche (USNA) SI413 - Class 6 Fall 2011 1 / 10 Objects in Scheme

More information

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? 2. How does memoization work?

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? 2. How does memoization work? STREAMS 10 COMPUTER SCIENCE 61AS Basics of Streams 1. What is a stream? 2. How does memoization work? 3. Is a cons-stream a special form? Practice with Streams 1. Define a procedure (ones) that, when run

More information

CSCI0170. Today s topics. Predicates Natural Number recursion Recursion Diagrams List recursion A first glance at the design recipe

CSCI0170. Today s topics. Predicates Natural Number recursion Recursion Diagrams List recursion A first glance at the design recipe CSCI0170 Predicates Natural Number recursion Recursion Diagrams List recursion A first glance at the design recipe Today s topics Lecture recorded; see course website. Predicates: things that test stuff

More information

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible

More information

Concepts of programming languages

Concepts of programming languages Concepts of programming languages Lecture 7 Wouter Swierstra 1 Last time Relating evaluation and types How to handle variable binding in embedded languages? 2 DSLs: approaches A stand-alone DSL typically

More information

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5 CS115 INTRODUCTION TO COMPUTER SCIENCE 1 Additional Notes Module 5 Example my-length (Slide 17) 2 (define (my-length alos) [(empty? alos) 0] [else (+ 1 (my-length (rest alos)))])) (my-length empty) alos

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Spring 203 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp

CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp CSE 341 Lecture 5 efficiency issues; tail recursion; print Ullman 3.3-3.4; 4.1 slides created by Marty Stepp http://www.cs.washington.edu/341/ Efficiency exercise Write a function called reverse that accepts

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

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

Discussion 4. Data Abstraction and Sequences

Discussion 4. Data Abstraction and Sequences Discussion 4 Data Abstraction and Sequences Data Abstraction: The idea of data abstraction is to conceal the representation of some data and to instead reveal a standard interface that is more aligned

More information

Recursion Chapter 4 Self-Reference. Recursive Definitions Inductive Proofs Implementing Recursion

Recursion Chapter 4 Self-Reference. Recursive Definitions Inductive Proofs Implementing Recursion Recursion Chapter 4 Self-Reference Recursive Definitions Inductive Proofs Implementing Recursion Imperative Algorithms Based on a basic abstract machine model - linear execution model - storage - control

More information

Repetition Through Recursion

Repetition Through Recursion Fundamentals of Computer Science I (CS151.02 2007S) Repetition Through Recursion Summary: In many algorithms, you want to do things again and again and again. For example, you might want to do something

More information

6.001 recitation 3/21/07

6.001 recitation 3/21/07 6.001 recitation 3/21/07 set-car! and set-cdr! ring problems more set-car!, set-cdr! problems 2 Dr. Kimberle Koile compound data mutation constructor: (cons x y) creates a new pair selectors: (car p) (cdr

More information

INTERPRETERS AND TAIL CALLS 9

INTERPRETERS AND TAIL CALLS 9 INTERPRETERS AND TAIL CALLS 9 COMPUTER SCIENCE 61A April 9, 2015 We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In order

More information

Pick any positive integer. If the integer is even, divide it by 2. If it is odd,

Pick any positive integer. If the integer is even, divide it by 2. If it is odd, Equal Groups Multiplying and Dividing Integers Learning Goals In this lesson, you will: Multiply integers. Divide integers. Pick any positive integer. If the integer is even, divide it by 2. If it is odd,

More information

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 7 Lambda Calculus Dan Grossman Spring 2011 Where we are Done: Syntax, semantics, and equivalence For a language with little more than loops and global variables Now:

More information

1. (15 points) Solve the decanting problem for containers of sizes 199 and 179; that is find integers x and y satisfying.

1. (15 points) Solve the decanting problem for containers of sizes 199 and 179; that is find integers x and y satisfying. May 9, 2003 Show all work Name There are 260 points available on this test 1 (15 points) Solve the decanting problem for containers of sizes 199 and 179; that is find integers x and y satisfying where

More information

CIS 194: Homework 6. Due Monday, February 25. Fibonacci numbers

CIS 194: Homework 6. Due Monday, February 25. Fibonacci numbers CIS 194: Homework 6 Due Monday, February 25 Files you should submit: Fibonacci.hs This week we learned about Haskell s lazy evaluation. This homework assignment will focus on one particular consequence

More information

Administrivia. Simple data types

Administrivia. Simple data types Administrivia Lists, higher order procedures, and symbols 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (mpp) Massachusetts Institute of Technology Project 0 was due today Reminder:

More information

Scheme as implemented by Racket

Scheme as implemented by Racket Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

More information

Discussion 11. Streams

Discussion 11. Streams Discussion 11 Streams A stream is an element and a promise to evaluate the rest of the stream. You ve already seen multiple examples of this and its syntax in lecture and in the books, so I will not dwell

More information

CS61A Notes Disc 11: Streams Streaming Along

CS61A Notes Disc 11: Streams Streaming Along CS61A Notes Disc 11: Streams Streaming Along syntax in lecture and in the book, so I will not dwell on that. Suffice it to say, streams is one of the most mysterious topics in CS61A, trust than whatever

More information

Macros & Streams Spring 2018 Discussion 9: April 11, Macros

Macros & Streams Spring 2018 Discussion 9: April 11, Macros CS 61A Macros & Streams Spring 2018 Discussion 9: April 11, 2018 1 Macros So far, we ve mostly explored similarities between the Python and Scheme languages. For example, the Scheme list data structure

More information

Principles of Programming Languages

Principles of Programming Languages Ben-Gurion University of the Negev Faculty of Natural Science Department of Computer Science Mira Balaban Lecture Notes March 29, 2017 Many thanks to Tamar Pinhas, Ami Hauptman, Eran Tomer, Barak Bar-Orion,

More information

STUDENT LESSON A9 Recursion

STUDENT LESSON A9 Recursion STUDENT LESSON A9 Recursion Java Curriculum for AP Computer Science, Student Lesson A9 1 STUDENT LESSON A9 Recursion INTRODUCTION: Recursion is the process of a method calling itself as part of the solution

More information

Fall 2017 December 4, 2017

Fall 2017 December 4, 2017 CS 61A Final Review Fall 2017 December 4, 2017 Instructions Form a small group. Start on the first problem. Check off with a helper or discuss your solution process with another group once everyone understands

More information

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang CS61A Notes Week 6B: Streams Streaming Along A stream is an element and a promise to evaluate the rest of the stream. You ve already seen multiple examples of this and its syntax in lecture and in the

More information

YOUR NAME PLEASE: *** SOLUTIONS ***

YOUR NAME PLEASE: *** SOLUTIONS *** YOUR NAME PLEASE: *** SOLUTIONS *** Computer Science 201b SAMPLE Exam 1 SOLUTIONS February 15, 2015 Closed book and closed notes. No electronic devices. Show ALL work you want graded on the test itself.

More information

HIERARCHICAL DATA What is a Tree? How is it different from a Deep List? When would you use one over the other?

HIERARCHICAL DATA What is a Tree? How is it different from a Deep List? When would you use one over the other? HIERARCHICAL DATA 5 COMPUTER SCIENCE 61AS Concepts and Definitions 1. What is a Tree? How is it different from a Deep List? When would you use one over the other? A Tree is an Abstract Data Type composed

More information

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add Using Symbols in Expressions (1) (define z y) z Symbol y z ==> y prints as (+ x 3) evaluate sub-expressions... PrimProc Number Number ( ) machine code to add 23 3 Number 26 apply... ==> 26 prints as 1

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

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list? More Scheme CS 331 Quiz 1. What is (car ((2) 3 4))? (2) 2. What is (cdr ((2) (3) (4)))? ((3)(4)) 3. What is (cons 2 (2 3 4))? (2 2 3 4) 4. What is the length of the list (()()()())? 4 5. Which element

More information

TAIL CALLS, ITERATORS, AND GENERATORS 11

TAIL CALLS, ITERATORS, AND GENERATORS 11 TAIL CALLS, ITERATORS, AND GENERATORS 11 COMPUTER SCIENCE 61A November 13, 214 1 Tail Calls Scheme implements tail-call optimization, which allows programmers to write recursive functions that use a constant

More information

Lisp Basic Example Test Questions

Lisp Basic Example Test Questions 2009 November 30 Lisp Basic Example Test Questions 1. Assume the following forms have been typed into the interpreter and evaluated in the given sequence. ( defun a ( y ) ( reverse y ) ) ( setq a (1 2

More information

CSE 341 Lecture 16. More Scheme: lists; helpers; let/let*; higher-order functions; lambdas

CSE 341 Lecture 16. More Scheme: lists; helpers; let/let*; higher-order functions; lambdas CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp http://www.cs.washington.edu/341/ Lists (list expr2... exprn) '(value1 value2...

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion A method calling itself Overview A new way of thinking about a problem Divide and conquer A powerful programming

More information

Programming Languages: Application and Interpretation

Programming Languages: Application and Interpretation Programming Languages: Application and Interpretation Version 5.0.1 August 3, 2010 This is the documentation for the software accompanying the textbook Programming Languages: Application and Interpretation

More information

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3... Recursion Recursion Overview A method calling itself A new way of thinking about a problem Divide and conquer A powerful programming paradigm Related to mathematical induction Example applications Factorial

More information

Whereweare. CS-XXX: Graduate Programming Languages. Lecture 7 Lambda Calculus. Adding data structures. Data + Code. What about functions

Whereweare. CS-XXX: Graduate Programming Languages. Lecture 7 Lambda Calculus. Adding data structures. Data + Code. What about functions Whereweare CS-XXX: Graduate Programming Languages Lecture 7 Lambda Calculus Done: Syntax, semantics, and equivalence For a language with little more than loops and global variables Now: Didn t IMP leave

More information

Programming Systems in Artificial Intelligence Functional Programming

Programming Systems in Artificial Intelligence Functional Programming Click to add Text Programming Systems in Artificial Intelligence Functional Programming Siegfried Nijssen 8/03/16 Discover thediscover world at the Leiden world University at Leiden University Overview

More information

Today's Lecture. Programming as the process of creating a new task-specific language. data abstractions procedure abstractions higher-order procedures

Today's Lecture. Programming as the process of creating a new task-specific language. data abstractions procedure abstractions higher-order procedures Today's Lecture Programming as the process of creating a new task-specific language data abstractions procedure abstractions higher-order procedures Themes to be integrated Data abstraction Separate use

More information

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page. MORE SCHEME COMPUTER SCIENCE MENTORS 61A October 30 to November 3, 2017 1 What Would Scheme Print? Solutions begin on the following page. 1. What will Scheme output? Draw box-and-pointer diagrams to help

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages Slides by Dana Fisman based on book by Mira Balaban and lecuture notes by Michael Elhadad Lesson 15 Type Inference Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172

More information

Fall 2018 Lecture N

Fall 2018 Lecture N 15-150 Fall 2018 Lecture N Tuesday, 20 November I m too lazy to figure out the correct number Stephen Brookes midterm2 Mean: 79.5 Std Dev: 18.4 Median: 84 today or, we could procrastinate lazy functional

More information

Functional Languages. Hwansoo Han

Functional Languages. Hwansoo Han Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

More information

Lambda Calculus as a Programming Language

Lambda Calculus as a Programming Language Cristian Giumale / Lecture Notes 1 Lambda Calculus as a Programming Language The Lambda calculus can be considered as the machine code of a particular computer. Call it the Lambda machine. As in conventional

More information

Sequentialising a concurrent program using continuation-passing style

Sequentialising a concurrent program using continuation-passing style Sequentialising a concurrent program using continuation-passing style Juliusz Chroboczek Université de Paris-Diderot (Paris 7) jch@pps.jussieu.fr 28 January 2012 1/44 Outline Everything you ever wanted

More information