Streams and Evalutation Strategies

Size: px
Start display at page:

Download "Streams and Evalutation Strategies"

Transcription

1 Data and Program Structure Streams and Evalutation Strategies Lecture V Ahmed Rezine Linköpings Universitet TDDA69, VT 2014

2 Lecture 2: Class descriptions - message passing ( define ( make-account balance ) ;; public methods ( define ( withdraw amount ) ( if (>= balance amount ) ( begin ( set! balance (- balance amount )) balance ) " Insufficient funds ")) ( define ( deposit amount ) ( set! balance (+ balance amount )) balance ) ;; message passing procedure ( define ( dispatch m) ( cond (( eq? m withdraw ) withdraw ) (( eq? m deposit ) deposit ) ( else ( error " Unknown request " m)))) dispatch ) >(define acc1 (make-account 100)) >(define acc2 (make-account 100)) >((acc1 withdraw) 40) 60 >((acc1 deposit) 60) 120 >((acc2 withdraw) 110) Insufficient funds >((acc1 deposit) 110) 10

3 Lecture 2: A half-adder ( define a ( make-wire )) ( define b ( make-wire )) ( define s ( make-wire )) ( define c ( make-wire )) ( define ( half-adder a b s c) ( let ((d ( make-wire )) (e ( make-wire ))) ( or-gate a b d) ( and-gate a b c) ( inverter c e) ( and-gate d e s) ok)) Figure : 3.25 in SICP

4 Lecture 2: A sample simulation > (define the-agenda (make-agenda)) > (define inverter-delay 2) > (define and-gate-delay 3) > (define or-gate-delay 5) > (define input-1 (make-wire)) > (define input-2 (make-wire)) > (define sum (make-wire)) > (define carry (make-wire)) > (probe sum sum) sum 0 New-value = 0 > (probe carry carry) > (set-signal! input-1 1) done > (propagate) sum 8 New-value = 1done > (set-signal! input-2 1) done > (propagate) carry 11 New-value = 1 sum 16 New-value = 0done carry 0 New-value = 0 > (half-adder input-1 input-2 sum carry) ok

5 Lecture 2: Fahrenheit-Celsius converter See Section in SICP for the implementation Recall 9C = 5(F-32) Captured by combining two multipliers, an adder and three constants constraints Figure : 3.28 in SICP

6 Lecture 2 : Fahrenheit-Celsius converter (cont.) ( define ( celsius-fahrenheit-converter c f) ( let ((u ( make-connector ))(v ( make-connector )) (w ( make-connector ))(x ( make-connector )) (y ( make-connector ))) ( multiplier c w u) ( multiplier v x u) ( adder v y f) ( constant 9 w) ( constant 5 x) ( constant 32 y) ok)) > (define C (make-connector)) > (define F (make-connector)) > (celsius-fahrenheit-converter C F) ok > (probe "Celsius" C) > (probe "Farenheit" F) > (set-value! C 25 user) Probe: Celsius = 25 Probe: Farenheit = 77 done > (forget-value! C user) Probe: Celsius =? Probe: Farenheit =? done > (set-value! F 212 user) Probe: Farenheit = 212 Probe: Celsius = 100 done

7 Outline Streams (SICP sec 3.5) Modeling the Modules Efficient Implementation Delayed evaluation and Parameter passing

8 Outline Streams (SICP sec 3.5) Modeling the Modules Efficient Implementation Delayed evaluation and Parameter passing

9 Streams We can use streams to achieve modularity with a new type of modeling: Similar to the way signal processing systems are described. Signals flow through the modules that perform different transformations We build sequences representing the history of the modeled system. The resulting system has a state without assignments or mutable data.

10 Example 1: sum odd squares of a tree s leaves Given a binary tree, compute the sum of the squares of its odd leaves: ( define ( sum- odd- squares tree ) (if ( leaf-node? tree ) (if ( odd? tree ) ( square tree ) 0) (+ ( sum- odd- squares ( left-branch tree )) ( sum- odd- squares ( right-branch tree )))))

11 Example 2: enumerate the odd Fibonacci numbers Given a natural n, build a list of all the odd Fibonacci numbers fib(k) where k is smaller or equal than n. ( define ( sum-odd-fibs n) ( define ( next k) (if (> k n) () ( let ((f ( fib k))) (if ( odd? f) ( cons f ( next (+ k 1))) ( next (+ k 1)))))) ( next 1))

12 Similarities when abstracting The two procedures are structurally very different. Several similarities when abstracting. When summing the squares of the odd leaves of a tree, the procedure: ( define ( sum-odd-squares tree ) (if ( leaf-node? tree ) (if ( odd? tree ) ( square tree ) 0) (+ ( sum-odd-squares ( left-branch tree )) ( sum-odd-squares ( right-branch tree ))))) Enumerates all leaves Keeps only the odd ones Squares them Accumulates + from 0

13 Similarities when abstracting (cont.) When enumerating the odd Fibonacci numbers, the procedure: ( define ( sum-odd-fibs n) ( define ( next k) (if (> k n) () ( let ((f ( fib k))) (if ( odd? f) ( cons f ( next (+ k 1))) ( next (+ k 1)))))) ( next 1)) Enumerates from 0 to n Compute Fibonacci numbers Filter them, keeping the odd ones Accumulates cons from ()

14 Similarities when abstracting (cont.) The two procedures fail to exhibit these flow structures. We build a modular solution based on higher order functions and let data flow between the modules.

15 Streams to increase conceptual clarity: (sum-odd-squares revisited) ( define ( sum-odd-squares tree ) ( sum ( map-square ( filter-odd ( enumerate-tree tree ))))) ( define ( sum-odd-squares tree ) (if ( leaf-node? tree ) (if ( odd? tree ) ( square tree ) 0) (+ ( sum-odd-squares ( left-branch tree )) ( sum-odd-squares ( right-branch tree )))))

16 Streams to increase conceptual clarity: (sum-odd-fibs revisited) ( define ( sum-odd-fibs n) ( accumulate-cons ( filter-odd ( map-fib ( enumerate-interval 1 n))))) ( define ( sum-odd-fibs n) ( define ( next k) (if (> k n) () ( let ((f ( fib k))) (if ( odd? f) ( cons f ( next (+ k 1))) ( next (+ k 1)))))) ( next 1))

17 Streams as flow of data Increase the conceptual clarity More elegant and succinct What data structure to use? What about efficiency? We will use the following building tools: Constructor: cons-stream Selectors: stream-car, stream-cdr Recognizer : stream-null? The empty object : the-empty-stream

18 Streams as flow of data (cont.) The description exactly matches the one for lists and sequences: cons-stream! cons stream-car! car stream-cdr! cdr stream-null?! null? the-empty-stream! () In the beginning, we can think of, and implement, streams as usual sequences. Later, we will adopt more efficient implementations that will even allow us to manipulate infinite sequences!

19 Outline Streams (SICP sec 3.5) Modeling the Modules Efficient Implementation Delayed evaluation and Parameter passing

20 enumerate-tree in sum-odd-squares We can now describe the procedure for summing the squares of the odd leaves of a tree with the new approach: ( define ( sum-odd-squares tree ) ( sum ( map-square ( filter-odd ( enumerate-tree tree ))))) ( define ( enumerate-tree tree ) (if ( leaf-node? tree ) ( cons-stream tree the-empty-stream ) ( append-streams ( enumerate-tree ( left-branch tree )) ( enumerate-tree ( right-branch tree )))))

21 enumerate-tree in sum-odd-squares (cont.) We can now describe the procedure for summing the squares of the odd leaves of a tree with the new approach: ( define ( sum-odd-squares tree ) ( sum ( map-square ( filter-odd ( enumerate-tree tree ))))) ( define ( append-streams s1 s2) ( if ( stream-null? s1) s2 ( cons-stream ( stream-car s1) ( append-streams ( stream-cdr s1) s2))))

22 filter-odd in sum-odd-squares ( define ( sum-odd-squares tree ) ( sum ( map-square ( filter-odd ( enumerate-tree tree ))))) ( define ( filter-odd s) ( cond (( stream-null? s) the-empty-stream ) (( odd? ( stream-car s)) ( cons-stream ( stream-car s) ( filter-odd ( stream-cdr s)))) ( else ( filter-odd ( stream-cdr s)))))

23 map-square in sum-odd-squares ( define ( sum-odd-squares tree ) ( sum ( map-square ( filter-odd ( enumerate-tree tree ))))) ( define ( map-square s) ( if ( stream-null? s) the-empty-stream ( cons-stream ( square ( stream-car s)) ( map-square ( stream-cdr s)))))

24 sum-streams in sum-odd-squares ( define ( sum-odd-squares tree ) ( sum ( map-square ( filter-odd ( enumerate-tree tree ))))) ( define ( sum-stream s) ( if ( stream-null? s) 0 (+ ( stream-car s) ( sum-stream ( stream-cdr s)))))

25 enumerate-interval in sum-odd-fibs We can also describe the procedure for building the sequence of all odd Fibonacci numbers Fib(k) where k n: ( define ( sum-odd-fibs n) ( accumulate-cons ( filter-odd ( map-fib ( enumerate-interval 1 n))))) ( define ( enumerate-interval low high ) ( if (> low high ) the-empty-stream ( cons-stream low ( enumerate-interval (+ low 1) high ))))

26 map-fib in sum-odd-fibs We can also describe the procedure for building the sequence of all odd Fibonacci numbers Fib(k) where k n: ( define ( sum-odd-fibs n) ( accumulate-cons ( filter-odd ( map-fib ( enumerate-interval 1 n))))) ( define ( map-fib s) ( if ( stream-null? s) the-empty-stream ( cons-stream ( fib ( stream-car s)) ( map-fib ( stream-cdr s)))))

27 accumulate-cons in sum-odd-fibs We can also describe the procedure for building the sequence of all odd Fibonacci numbers Fib(k) where k n: ( define ( sum-odd-fibs n) ( accumulate-cons ( filter-odd ( map-fib ( enumerate-interval 1 n))))) ( define ( accumulate-cons s) ( if ( stream-null? s) () ( cons ( stream-car s) ( accumulate-cons ( stream-cdr s)))))

28 Higher order functions for streams: accumulate We can abstract stream operations such as sum, product and accumulate (see labs for corresponding abstractions on lists) ( define ( accumulate combiner initial-value stream ) ( if ( stream-null? stream ) initial-value ( combiner ( stream-car stream ) ( accumulate combiner initial-value ( stream-cdr stream ))))) ( define ( sum-stream stream ) ( accumulate + 0 stream )) ( define ( accumulate-cons stream ) ( accumulate cons () stream ))

29 Higher order functions for streams: stream-map We can abstract stream operations such as sum, product and accumulate (see labs for corresponding abstractions on lists) ( define ( stream-map proc stream ) ( if ( stream-null? stream ) the-empty-stream ( cons-stream ( proc ( stream-car stream )) ( stream-map proc ( stream-cdr stream ))))) ( define ( map-square s) ( stream-map square s)) ( define ( map-fib s) ( stream-map fib s))

30 Higher order functions for streams: stream-filter We can abstract stream operations such as sum, product and accumulate (see labs for corresponding abstractions on lists) ( define ( stream-filter predicate stream ) ( cond (( stream-null? stream ) the-empty-stream ) (( predicate ( stream-car stream )) ( cons-stream ( stream-car stream ) ( stream-filter predicate ( stream-cdr stream )))) ( else ( stream-filter predicate ( stream-cdr stream ))))) ( define ( filter-odd s) ( stream-filter odd? s))

31 Some examples ( define ( prod-square-odd-elements-stream stream ) ( accumulate * 1 ( stream-map square ( stream-filter odd? stream )))) ( define ( salary-of-highest-paid-programmer records ) ( accumulate max 0 ( stream-map salary ( stream-filter programmer? records ))))

32 Outline Streams (SICP sec 3.5) Modeling the Modules Efficient Implementation Delayed evaluation and Parameter passing

33 Implementing streams We can indeed represent streams as lists: Constructor: cons for cons-stream Selectors: car and cdr for resp. stream-car and stream-cdr Recognizer : null? for stream-null? The empty object : () for the-empty-stream This representation is very inefficient both wrt. time and space

34 Example 1: summing prime numbers ( define ( sum-primes1 a b) ( define ( iter count accum ) ( cond ((> count b) accum ) (( prime? count ) ( iter (+ count 1) (+ count accum ))) ( else ( iter (+ count 1) accum )))) ( iter a 0)) ( define ( sum-primes2 a b) ( sum-stream ( stream-filter prime? ( enumerate-interval a b)))) sum-primes1 only stores the sum being calculated (and not the list of integers, etc)

35 Example 2: finding the second prime Find the second prime number between and : ( stream-car ( stream-cdr ( stream-filter prime? ( enumerate-interval ) ))) An incremental computation would be more efficient because it would interleave enumeration and filtering and would stop when it reaches the second prime.

36 Streams implementation Formulate programs elegantly as sequence manipulations, with the efficiency of incremental computation cons-stream constructs streams partially: just a first element and enough information to construct the rest stream-cdr forces the computation of the second element Elements of the stream are only generated if needed. This is transparent to the user: on the surface streams are lists with a different syntax Transparently and automatically interleave the construction of a stream and its use

37 Streams implementation: help functions (delay expr): returns a delayed object with enough information to evaluate expr if needed. A delayed object can be thought of as a promise. delay is a special form and can be implemented as a ( lambda () expr ) (force delayed-object): Evaluates the delayed object ( define ( force delayed- object ) ( delayed-object ))

38 Streams implementation ;; cons- stream is a " special form " ;; ( cons- stream a b) corresponds to ( cons a ( delay b)) ( define ( stream- car stream ) ( car stream )) ( define ( stream- cdr stream ) ( force ( cdr stream ))) ( define the- empty- stream ()) ( define stream- null? null?)

39 Example2: finding primes revisited Streams allow for a demand-driven evaluation model. Only the needed cells for finding the result are evaluated. ( stream- car ( stream- cdr ( stream- filter prime? ( enumerate- interval ) ))) In the primes example, the numbers 10000, 10001, 10002, 10003, 10004, and will be generated and rejected by stream-filter. Then is a prime number followed by a non-prime and finally the second prime is generated and returned as the result. Intermediary results that are not needed are not generated!

40 Memoization: an important optimization The same evaluations will be forced several times if we were to reuse the beginning of a stream. ( define s ( cons- stream 1 ( cons- stream 2 ( cons- stream 3 the-empty-stream )))) result in s = (1 "lambda () (cons-stream 2...)"). Now evaluating: ( stream-car ( stream-cdr s)) ( stream-cdr ( stream-cdr s)) (lambda () (cons-stream 2...)) is evaluated twice.

41 Memoization: an important optimization (cont.) Instead of re-evaluating, remember the result of the first evaluation of the delayed argument by replacing (delay expr) with (memo-proc (lambda () expr)) where : ( define ( memo- proc proc ) ( let (( already-run? false ) ( result false )) ( lambda () (if ( not already-run?) ( begin ( set! result ( proc )) ( set! already-run? true ) result ) result )))) Compare : call-by-name: evaluate each time call-by-need: evaluate once, remember the result

42 Infinite streams! ( define ( integers-starting-from n) ( cons- stream n ( integers-starting-from (+ n 1)))) A recursive function without a base case! ( define integers ( integers-starting-from 1)) ( define ( stream-ref stream n) (if (= n 0) ( stream-car stream ) ( stream-ref ( stream-cdr stream ) (- n 1)))) ( define ( nth-prime n) ( stream-ref ( stream-filter prime? integers ) (- n 1)))

43 Infinite streams ;; Fibonacci numbers ( define ( fib-gen a b) ( cons-stream a ( fib-gen b (+ a b)))) ( define fibs ( fib-gen 0 1)) ;; add streams ( define ( add-streams s1 s2) ( cond (( stream-null? s1) s2) (( stream-null? s2) s1) ( else ( cons-stream (+ ( stream-car s1) ( stream-car s2)) ( add-streams ( stream-cdr s1) ( stream-cdr s2)))))) ( define ones ( cons-stream 1 ones )) ( define mysterious ( cons-stream 1 ( add-streams ones mysterious )))

44 Infinite streams Yet another definition of the Fibonacci numbers ( define fibs ( cons- stream 0 ( cons- stream 1 ( add-streams ( stream-cdr fibs ) fibs ))))

45 Sieve of Erastothenes Generate all primes by starting from all naturals larger than 1 The first natural (2) is a prime, filter out all its multiples The first element (3) is a prime. Filter out all naturals that are divisible by 3 The first element (5) is a prime. Filter... ( define ( sieve streams ) ( cons- stream ( stream- car stream ) ( sieve ( stream- filter ( lambda (x) ( not ( divisible? x ( stream-car stream )))) ( stream-cdr stream )))))

46 Sieve of Erastothenes (cont.) ( define ( sieve streams ) ( cons- stream ( stream- car stream ) ( sieve ( stream- filter ( lambda (x) ( not ( divisible? x ( stream-car stream )))) ( stream-cdr stream ))))) ( define primes ( sieve ( integers-starting-from 2))) ( stream- ref primes 100) > 547

47 History without mutation We can build sequences that represent the history of the modeled system. We can now model systems with state without using assignment or mutable data (see example 3.5.3) For instance, the random number generator (example 3.5.5): with objects and state: ( define random-init...) ( define ( rand-update x)... ) ( define rand ( let ((x random-init )) ( lambda () ( set! x ( rand-update x)) x))) ( rand )

48 History without mutation We can build sequences that represent the history of the modeled system. We can now model systems with state without using assignment or mutable data (see example 3.5.3) For instance, the random number generator (example 3.5.5): with streams: ( define random- numbers ( cons- stream random- init ( stream- map rand- update random-numbers ))) ( stream- ref random- numbers 10)

49 Outline Streams (SICP sec 3.5) Modeling the Modules Efficient Implementation Delayed evaluation and Parameter passing

50 Evaluation strategies here only cons had delayed arguments why not delay the evaluation of all arguments? when to force the evaluation? Evaluate according to normal order! in Algol 60, it was possible to pass parameters with a call-by-name Functional languages (e.g. lazy-ml, Haskel) use lazy evaluation. Parameters are then evaluated in a call-by-need The usual evaluation strategy is called call-by-value (eager evaluation)

51 Strict and non-strict functions Let? mean an undefined value, e.g. resulting from the evaluation of an inappropriate value or from a non-terminating computation ((sqrt -4), (/10 0), (factorial -1), etc.) A function is strict if it is undefined if any of its arguments is undefined. Otherwise, the function is not strict: (if? 10 20) =? (if false? 20) = 20 (if true 10? ) = 10

52 Delayed evaluation - lazy evaluations Normal order evaluation ( SICP p16 and p350 ). ( define ( sum-of-squares x y) (+ ( square x) ( square x))) ( define ( square x) (* x x)) > ( sum-of-squares (+ 5 1) (* 5 2)) --> (+ ( square (+ 5 1)) ( square (* 5 2))) --> (+ (* (+ 5 1) (* 5 1)) (* (+ 5 1) (* 5 1))) -->... ( define ( foo x y) (if (= x 1) y x)) > (f 2 (/ 10 0)) --> (if (= 2 1) (/ 10 0) 2) --> 2

53 Models of parameter passing call-by-value, call-by-name, call-by-need, call-by-reference,... call-by-name: Copying rule in Algol 60 procedure f(x, y); value x; name y; integer x,y; y:= 10 * x + y; integer inut, in; inut := 3; in := 5; f(in, inut ); print ( inut ); inut is replaced by y (using static binding) also called call-by-name thunks (footnote p324 SICP) inut := 10 * 5 + inut Ada: by-constant-value, by-result, by-copy-restore procedure f(in x, out y, in out z);

54 call-by-name and Jensen s device in Algol procedure Sigma ( start, stop, index, expr, sum ); value start, stop ; integer start, stop, index ; real expr, sum ; comment index, expr, sum are passed by name begin sum := 0; for index := start step 1 until stop do sum := sum + expr end ; comment when called with : Sigma (1, 100, i, 1/i^2, s) comment results in s := 0; for i := 1 step 1 until 100 do s := s + 1/ i^2 We will get back to this in lab 5 and lazy evaluation

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

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

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

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

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

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

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

4.2 Variations on a Scheme -- Lazy Evaluation

4.2 Variations on a Scheme -- Lazy Evaluation [Go to first, previous, next page; contents; index] 4.2 Variations on a Scheme -- Lazy Evaluation Now that we have an evaluator expressed as a Lisp program, we can experiment with alternative choices in

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

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

A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

More information

2.2 Hierarchical Data and the Closure Property

2.2 Hierarchical Data and the Closure Property [Go to first, previous, next page; contents; index] 2.2 Hierarchical Data and the Closure Property As we have seen, pairs provide a primitive ``glue'' that we can use to construct compound data objects.

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

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

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

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

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

Lazy Evaluation and Parameter Transfer

Lazy Evaluation and Parameter Transfer Cristian Giumale / Lecture Notes Lazy Evaluation and Parameter Transfer Scheme comes with two interesting predefined functions: delay and force. The basic purpose of delay is to postpone the evaluation

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

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. Thunks, Laziness, Streams, Memoization. Adapted from Dan Grossman s PL class, U. of Washington

Programming Languages. Thunks, Laziness, Streams, Memoization. Adapted from Dan Grossman s PL class, U. of Washington Programming Languages Thunks, Laziness, Streams, Memoization Adapted from Dan Grossman s PL class, U. of Washington You ve been lied to Everything that looks like a function call in Racket is not necessarily

More information

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action. Deferred operations Continuations 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (define the-cons (cons 1 #f)) (set-cdr! the-cons the-cons) (define (run-in-circles l) (+

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

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

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

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

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

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

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

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

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

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

cs61amt2_4 CS 61A Midterm #2 ver March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name

cs61amt2_4 CS 61A Midterm #2 ver March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name CS 61A Midterm #2 ver1.03 -- March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name Look at the edge of your seat. Write your ROOM, seat row and number. Your row number

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

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

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

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

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

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

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

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

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules Haskell: From Basic to Advanced Part 2 Type Classes, Laziness, IO, Modules Qualified types In the types schemes we have seen, the type variables were universally quantified, e.g. ++ :: [a] -> [a] -> [a]

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

User-defined Functions. Conditional Expressions in Scheme

User-defined Functions. Conditional Expressions in Scheme User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

More information

CS 61A Midterm #2 ver March 2, 1998 Exam version: A. Your name. login: cs61a- Discussion section number. TA's name

CS 61A Midterm #2 ver March 2, 1998 Exam version: A. Your name. login: cs61a- Discussion section number. TA's name CS 61A Midterm #2 ver1.03 -- March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name Look at the edge of your seat. Write your ROOM, seat row and number. Your row number

More information

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Scheme in Scheme: The Metacircular Evaluator Eval and Apply Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,

More information

University of Massachusetts Lowell

University of Massachusetts Lowell University of Massachusetts Lowell 91.301: Organization of Programming Languages Fall 2002 Quiz 1 Solutions to Sample Problems 2 91.301 Problem 1 What will Scheme print in response to the following statements?

More information

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in

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

Functional Programming - 2. Higher Order Functions

Functional Programming - 2. Higher Order Functions Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class

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

Racket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013

Racket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013 Racket: Macros Advanced Functional Programming Jean-Noël Monette November 2013 1 Today Macros pattern-based macros Hygiene Syntax objects and general macros Examples 2 Macros (According to the Racket Guide...)

More information

MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science. Issued: Wed. 26 April 2017 Due: Wed.

MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science. Issued: Wed. 26 April 2017 Due: Wed. ps.txt Fri Apr 07 14:24:11 2017 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.945 Spring 2017 Problem Set 9 Issued: Wed. 26 April 2017 Due: Wed. 12

More information

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the

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

Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS

Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS This document contains solutions to the problems on the final exam review problems posted earlier except for

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

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator. .00 SICP Interpretation part Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment Environment as explicit parameter Defining new procedures Why do

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

regsim.scm ~/umb/cs450/ch5.base/ 1 11/11/13

regsim.scm ~/umb/cs450/ch5.base/ 1 11/11/13 1 File: regsim.scm Register machine simulator from section 5.2 of STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS This file can be loaded into Scheme as a whole. Then you can define and simulate machines

More information

Building a system for symbolic differentiation

Building a system for symbolic differentiation Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)

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

Chapter 15 Functional Programming Languages

Chapter 15 Functional Programming Languages Chapter 15 Functional Programming Languages Fundamentals of Functional Programming Languages Introduction to Scheme A programming paradigm treats computation as the evaluation of mathematical functions.

More information

Berkeley Scheme s OOP

Berkeley Scheme s OOP Page < 1 > Berkeley Scheme s OOP Introduction to Mutation If we want to directly change the value of a variable, we need a new special form, set! (pronounced set BANG! ). (set! )

More information

Introduction to Scheme

Introduction to Scheme How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

More information

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

Programming Languages

Programming Languages Programming Languages Tevfik Koşar Lecture - XIII March 2 nd, 2006 1 Roadmap Functional Languages Lambda Calculus Intro to Scheme Basics Functions Bindings Equality Testing Searching 2 1 Functional Languages

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

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) What is the Metacircular Evaluator? It is the best part

More information

6.001, Spring Semester, 1998, Final Exam Your Name: 2 Question 1 (12 points): Each of the parts below should be treated as independent. For each part,

6.001, Spring Semester, 1998, Final Exam Your Name: 2 Question 1 (12 points): Each of the parts below should be treated as independent. For each part, 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Spring Semester, 1998, Final Exam Your Name: Open

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

Functional Programming

Functional Programming Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax Scheme Tutorial Introduction Scheme is an imperative language with a functional core. The functional core is based on the lambda calculus. In this chapter only the functional core and some simple I/O is

More information

Example Scheme Function: equal

Example Scheme Function: equal ICOM 4036 Programming Languages Functional Programming Languages Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming Language: LISP Introduction to

More information

COP4020 Programming Assignment 1 - Spring 2011

COP4020 Programming Assignment 1 - Spring 2011 COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to

More information

Sample Final Exam Questions

Sample Final Exam Questions 91.301, Organization of Programming Languages Fall 2015, Prof. Yanco Sample Final Exam Questions Note that the final is a 3 hour exam and will have more questions than this handout. The final exam will

More information

Lexical vs. Dynamic Scope

Lexical vs. Dynamic Scope Intro Lexical vs. Dynamic Scope where do I point to? Remember in Scheme whenever we call a procedure we pop a frame and point it to where the procedure points to (its defining environment). This is called

More information

Principles of Programming Languages

Principles of Programming Languages 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 www.cs.bgu.ac.il/~ppl172 1 Lazy

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

4/19/2018. Chapter 11 :: Functional Languages

4/19/2018. Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken by Alan Turing, Alonzo Church, Stephen

More information

FP Foundations, Scheme

FP Foundations, Scheme FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

More information

Building a system for symbolic differentiation

Building a system for symbolic differentiation Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)

More information

Box-and-arrow Diagrams

Box-and-arrow Diagrams Box-and-arrow Diagrams 1. Draw box-and-arrow diagrams for each of the following statements. What needs to be copied, and what can be referenced with a pointer? (define a ((squid octopus) jelly sandwich))

More information

CSE341 Autumn 2017, Final Examination December 12, 2017

CSE341 Autumn 2017, Final Examination December 12, 2017 CSE341 Autumn 2017, Final Examination December 12, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for both sides of one 8.5x11in piece of paper. Please

More information

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan 1 Reading SICP, page 11-19, Section 1.1.6 Little Schemer, Chapter 2 2 The Idea of Syntax Abstraction Problem. Often programming tasks are repetitive,

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

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

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

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am. The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

More information

An Introduction to Scheme

An Introduction to Scheme An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

More information

Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson Introduction to Functional Programming in Racket CS 550 Programming Languages Jeremy Johnson 1 Objective To introduce functional programming in racket Programs are functions and their semantics involve

More information

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7 Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

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

CS403: Programming Languages. Assignment 3. Rought Draft

CS403: Programming Languages. Assignment 3. Rought Draft CS403: Programming Languages Assignment 3 Rought Draft Preliminary information This is your third Scam assignment. To run your code, use the following command: or scam FILENAME scam -r FILENAME where FILENAME

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

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

CS3L Summer 2011 Final Exam, Part 2 You may leave when finished; or, you must stop promptly at 12:20

CS3L Summer 2011 Final Exam, Part 2 You may leave when finished; or, you must stop promptly at 12:20 CS3L Summer 2011 Final Exam, Part 2 You may leave when finished; or, you must stop promptly at 12:20 Name: Login: cs3- First names of the people to your left and right, if any: Left: Right: 1. If you have

More information

Exercise 1 ( = 24 points)

Exercise 1 ( = 24 points) 1 Exercise 1 (4 + 5 + 4 + 6 + 5 = 24 points) The following data structure represents polymorphic binary trees that contain values only in special Value nodes that have a single successor: data Tree a =

More information