Streams and Evalutation Strategies


 Elisabeth Long
 1 years ago
 Views:
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 ( makeaccount 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 (makeaccount 100)) >(define acc2 (makeaccount 100)) >((acc1 withdraw) 40) 60 >((acc1 deposit) 60) 120 >((acc2 withdraw) 110) Insufficient funds >((acc1 deposit) 110) 10
3 Lecture 2: A halfadder ( define a ( makewire )) ( define b ( makewire )) ( define s ( makewire )) ( define c ( makewire )) ( define ( halfadder a b s c) ( let ((d ( makewire )) (e ( makewire ))) ( orgate a b d) ( andgate a b c) ( inverter c e) ( andgate d e s) ok)) Figure : 3.25 in SICP
4 Lecture 2: A sample simulation > (define theagenda (makeagenda)) > (define inverterdelay 2) > (define andgatedelay 3) > (define orgatedelay 5) > (define input1 (makewire)) > (define input2 (makewire)) > (define sum (makewire)) > (define carry (makewire)) > (probe sum sum) sum 0 Newvalue = 0 > (probe carry carry) > (setsignal! input1 1) done > (propagate) sum 8 Newvalue = 1done > (setsignal! input2 1) done > (propagate) carry 11 Newvalue = 1 sum 16 Newvalue = 0done carry 0 Newvalue = 0 > (halfadder input1 input2 sum carry) ok
5 Lecture 2: FahrenheitCelsius converter See Section in SICP for the implementation Recall 9C = 5(F32) Captured by combining two multipliers, an adder and three constants constraints Figure : 3.28 in SICP
6 Lecture 2 : FahrenheitCelsius converter (cont.) ( define ( celsiusfahrenheitconverter c f) ( let ((u ( makeconnector ))(v ( makeconnector )) (w ( makeconnector ))(x ( makeconnector )) (y ( makeconnector ))) ( multiplier c w u) ( multiplier v x u) ( adder v y f) ( constant 9 w) ( constant 5 x) ( constant 32 y) ok)) > (define C (makeconnector)) > (define F (makeconnector)) > (celsiusfahrenheitconverter C F) ok > (probe "Celsius" C) > (probe "Farenheit" F) > (setvalue! C 25 user) Probe: Celsius = 25 Probe: Farenheit = 77 done > (forgetvalue! C user) Probe: Celsius =? Probe: Farenheit =? done > (setvalue! 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 ( leafnode? tree ) (if ( odd? tree ) ( square tree ) 0) (+ ( sum odd squares ( leftbranch tree )) ( sum odd squares ( rightbranch 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 ( sumoddfibs 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 ( sumoddsquares tree ) (if ( leafnode? tree ) (if ( odd? tree ) ( square tree ) 0) (+ ( sumoddsquares ( leftbranch tree )) ( sumoddsquares ( rightbranch 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 ( sumoddfibs 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: (sumoddsquares revisited) ( define ( sumoddsquares tree ) ( sum ( mapsquare ( filterodd ( enumeratetree tree ))))) ( define ( sumoddsquares tree ) (if ( leafnode? tree ) (if ( odd? tree ) ( square tree ) 0) (+ ( sumoddsquares ( leftbranch tree )) ( sumoddsquares ( rightbranch tree )))))
16 Streams to increase conceptual clarity: (sumoddfibs revisited) ( define ( sumoddfibs n) ( accumulatecons ( filterodd ( mapfib ( enumerateinterval 1 n))))) ( define ( sumoddfibs 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: consstream Selectors: streamcar, streamcdr Recognizer : streamnull? The empty object : theemptystream
18 Streams as flow of data (cont.) The description exactly matches the one for lists and sequences: consstream! cons streamcar! car streamcdr! cdr streamnull?! null? theemptystream! () 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 enumeratetree in sumoddsquares We can now describe the procedure for summing the squares of the odd leaves of a tree with the new approach: ( define ( sumoddsquares tree ) ( sum ( mapsquare ( filterodd ( enumeratetree tree ))))) ( define ( enumeratetree tree ) (if ( leafnode? tree ) ( consstream tree theemptystream ) ( appendstreams ( enumeratetree ( leftbranch tree )) ( enumeratetree ( rightbranch tree )))))
21 enumeratetree in sumoddsquares (cont.) We can now describe the procedure for summing the squares of the odd leaves of a tree with the new approach: ( define ( sumoddsquares tree ) ( sum ( mapsquare ( filterodd ( enumeratetree tree ))))) ( define ( appendstreams s1 s2) ( if ( streamnull? s1) s2 ( consstream ( streamcar s1) ( appendstreams ( streamcdr s1) s2))))
22 filterodd in sumoddsquares ( define ( sumoddsquares tree ) ( sum ( mapsquare ( filterodd ( enumeratetree tree ))))) ( define ( filterodd s) ( cond (( streamnull? s) theemptystream ) (( odd? ( streamcar s)) ( consstream ( streamcar s) ( filterodd ( streamcdr s)))) ( else ( filterodd ( streamcdr s)))))
23 mapsquare in sumoddsquares ( define ( sumoddsquares tree ) ( sum ( mapsquare ( filterodd ( enumeratetree tree ))))) ( define ( mapsquare s) ( if ( streamnull? s) theemptystream ( consstream ( square ( streamcar s)) ( mapsquare ( streamcdr s)))))
24 sumstreams in sumoddsquares ( define ( sumoddsquares tree ) ( sum ( mapsquare ( filterodd ( enumeratetree tree ))))) ( define ( sumstream s) ( if ( streamnull? s) 0 (+ ( streamcar s) ( sumstream ( streamcdr s)))))
25 enumerateinterval in sumoddfibs We can also describe the procedure for building the sequence of all odd Fibonacci numbers Fib(k) where k n: ( define ( sumoddfibs n) ( accumulatecons ( filterodd ( mapfib ( enumerateinterval 1 n))))) ( define ( enumerateinterval low high ) ( if (> low high ) theemptystream ( consstream low ( enumerateinterval (+ low 1) high ))))
26 mapfib in sumoddfibs We can also describe the procedure for building the sequence of all odd Fibonacci numbers Fib(k) where k n: ( define ( sumoddfibs n) ( accumulatecons ( filterodd ( mapfib ( enumerateinterval 1 n))))) ( define ( mapfib s) ( if ( streamnull? s) theemptystream ( consstream ( fib ( streamcar s)) ( mapfib ( streamcdr s)))))
27 accumulatecons in sumoddfibs We can also describe the procedure for building the sequence of all odd Fibonacci numbers Fib(k) where k n: ( define ( sumoddfibs n) ( accumulatecons ( filterodd ( mapfib ( enumerateinterval 1 n))))) ( define ( accumulatecons s) ( if ( streamnull? s) () ( cons ( streamcar s) ( accumulatecons ( streamcdr 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 initialvalue stream ) ( if ( streamnull? stream ) initialvalue ( combiner ( streamcar stream ) ( accumulate combiner initialvalue ( streamcdr stream ))))) ( define ( sumstream stream ) ( accumulate + 0 stream )) ( define ( accumulatecons stream ) ( accumulate cons () stream ))
29 Higher order functions for streams: streammap We can abstract stream operations such as sum, product and accumulate (see labs for corresponding abstractions on lists) ( define ( streammap proc stream ) ( if ( streamnull? stream ) theemptystream ( consstream ( proc ( streamcar stream )) ( streammap proc ( streamcdr stream ))))) ( define ( mapsquare s) ( streammap square s)) ( define ( mapfib s) ( streammap fib s))
30 Higher order functions for streams: streamfilter We can abstract stream operations such as sum, product and accumulate (see labs for corresponding abstractions on lists) ( define ( streamfilter predicate stream ) ( cond (( streamnull? stream ) theemptystream ) (( predicate ( streamcar stream )) ( consstream ( streamcar stream ) ( streamfilter predicate ( streamcdr stream )))) ( else ( streamfilter predicate ( streamcdr stream ))))) ( define ( filterodd s) ( streamfilter odd? s))
31 Some examples ( define ( prodsquareoddelementsstream stream ) ( accumulate * 1 ( streammap square ( streamfilter odd? stream )))) ( define ( salaryofhighestpaidprogrammer records ) ( accumulate max 0 ( streammap salary ( streamfilter 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 consstream Selectors: car and cdr for resp. streamcar and streamcdr Recognizer : null? for streamnull? The empty object : () for theemptystream This representation is very inefficient both wrt. time and space
34 Example 1: summing prime numbers ( define ( sumprimes1 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 ( sumprimes2 a b) ( sumstream ( streamfilter prime? ( enumerateinterval a b)))) sumprimes1 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 : ( streamcar ( streamcdr ( streamfilter prime? ( enumerateinterval ) ))) 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 consstream constructs streams partially: just a first element and enough information to construct the rest streamcdr 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 delayedobject): Evaluates the delayed object ( define ( force delayed object ) ( delayedobject ))
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 demanddriven 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 streamfilter. Then is a prime number followed by a nonprime 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 theemptystream )))) result in s = (1 "lambda () (consstream 2...)"). Now evaluating: ( streamcar ( streamcdr s)) ( streamcdr ( streamcdr s)) (lambda () (consstream 2...)) is evaluated twice.
41 Memoization: an important optimization (cont.) Instead of reevaluating, remember the result of the first evaluation of the delayed argument by replacing (delay expr) with (memoproc (lambda () expr)) where : ( define ( memo proc proc ) ( let (( alreadyrun? false ) ( result false )) ( lambda () (if ( not alreadyrun?) ( begin ( set! result ( proc )) ( set! alreadyrun? true ) result ) result )))) Compare : callbyname: evaluate each time callbyneed: evaluate once, remember the result
42 Infinite streams! ( define ( integersstartingfrom n) ( cons stream n ( integersstartingfrom (+ n 1)))) A recursive function without a base case! ( define integers ( integersstartingfrom 1)) ( define ( streamref stream n) (if (= n 0) ( streamcar stream ) ( streamref ( streamcdr stream ) ( n 1)))) ( define ( nthprime n) ( streamref ( streamfilter prime? integers ) ( n 1)))
43 Infinite streams ;; Fibonacci numbers ( define ( fibgen a b) ( consstream a ( fibgen b (+ a b)))) ( define fibs ( fibgen 0 1)) ;; add streams ( define ( addstreams s1 s2) ( cond (( streamnull? s1) s2) (( streamnull? s2) s1) ( else ( consstream (+ ( streamcar s1) ( streamcar s2)) ( addstreams ( streamcdr s1) ( streamcdr s2)))))) ( define ones ( consstream 1 ones )) ( define mysterious ( consstream 1 ( addstreams ones mysterious )))
44 Infinite streams Yet another definition of the Fibonacci numbers ( define fibs ( cons stream 0 ( cons stream 1 ( addstreams ( streamcdr 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 ( streamcar stream )))) ( streamcdr stream )))))
46 Sieve of Erastothenes (cont.) ( define ( sieve streams ) ( cons stream ( stream car stream ) ( sieve ( stream filter ( lambda (x) ( not ( divisible? x ( streamcar stream )))) ( streamcdr stream ))))) ( define primes ( sieve ( integersstartingfrom 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 randominit...) ( define ( randupdate x)... ) ( define rand ( let ((x randominit )) ( lambda () ( set! x ( randupdate 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 randomnumbers ))) ( 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 callbyname Functional languages (e.g. lazyml, Haskel) use lazy evaluation. Parameters are then evaluated in a callbyneed The usual evaluation strategy is called callbyvalue (eager evaluation)
51 Strict and nonstrict functions Let? mean an undefined value, e.g. resulting from the evaluation of an inappropriate value or from a nonterminating 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 ( sumofsquares x y) (+ ( square x) ( square x))) ( define ( square x) (* x x)) > ( sumofsquares (+ 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 callbyvalue, callbyname, callbyneed, callbyreference,... callbyname: 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 callbyname thunks (footnote p324 SICP) inut := 10 * 5 + inut Ada: byconstantvalue, byresult, bycopyrestore procedure f(in x, out y, in out z);
54 callbyname 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
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 informationStreams, 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 informationStreams. 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 informationNormal 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 informationSCHEME 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 information6.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 informationIntroduction 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 informationSummer 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 informationFall 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 information4.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 informationCS61A 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 informationOrganization 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 informationA 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 information2.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 informationITERATORS 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 informationProblem 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 informationCS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five boxandarrow diagrams.
CS 61A, Fall, 2002, Midterm #2, L. Rowe 1. (10 points, 1 point each part) Consider the following five boxandarrow 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 informationSCHEME 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 informationFall 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 informationLazy 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 informationStreams 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 informationCS 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 informationProgramming 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 informationDeferred 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 thecons (cons 1 #f)) (setcdr! thecons thecons) (define (runincircles l) (+
More informationDiscussion 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 informationProcedural 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 informationSCHEME 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 information6.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 informationCS61A 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 informationAn 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 informationSCHEME 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 informationCOP4020 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 informationFunctional 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 informationSCHEME 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 informationcs61amt2_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 informationScheme 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 informationSTREAMS 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 consstream a special form? Practice with Streams 1. Define a procedure (ones) that, when run
More informationClass 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 informationSpring 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 informationChapter 15. Functional Programming Languages
Chapter 15 Functional Programming Languages Copyright 2009 AddisonWesley. All rights reserved. 12 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages
More informationSTREAMS 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 informationCPS 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 informationHaskell: 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 informationYOUR 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 informationUserdefined Functions. Conditional Expressions in Scheme
Userdefined 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 informationCS 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 informationScheme 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 informationUniversity 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 informationPrinciples 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 informationLECTURE 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 informationFunctional Programming  2. Higher Order Functions
Functional Programming  2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class
More informationCSCC24 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 Lisplike Languages
More informationRacket: Macros. Advanced Functional Programming. JeanNoël Monette. November 2013
Racket: Macros Advanced Functional Programming JeanNoël Monette November 2013 1 Today Macros patternbased macros Hygiene Syntax objects and general macros Examples 2 Macros (According to the Racket Guide...)
More informationMASSACHVSETTS 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 information11/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 informationLecture 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 informationWellesley 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 informationCSC324 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 informationWhy 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 informationFunctional 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 informationregsim.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 informationBuilding 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 informationNotes 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 informationChapter 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 informationBerkeley 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 informationIntroduction 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 informationJVM 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 informationProgramming 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 informationScheme 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 informationCS61A 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 information6.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 informationComputer 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 informationFunctional 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 informationIntroduction 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 informationScheme 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 informationExample 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 informationCOP4020 Programming Assignment 1  Spring 2011
COP4020 Programming Assignment 1  Spring 2011 In this programming assignment we design and implement a small imperative programming language MicroPL. To execute MircoPL code we translate the code to
More informationSample 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 informationLexical 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 informationPrinciples 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 informationScheme 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 information4/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 informationFP 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 informationBuilding 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 informationBoxandarrow Diagrams
Boxandarrow Diagrams 1. Draw boxandarrow 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 informationCSE341 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 closedbook, closednote, etc. except for both sides of one 8.5x11in piece of paper. Please
More informationCS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan
CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan 1 Reading SICP, page 1119, Section 1.1.6 Little Schemer, Chapter 2 2 The Idea of Syntax Abstraction Problem. Often programming tasks are repetitive,
More informationInterpreters 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 informationTyped Racket: Racket with Static Types
Typed Racket: Racket with Static Types Version 5.0.2 Sam TobinHochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type
More informationFunctional Programming. Overview. Topics. Definition nth 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 informationAnnouncements. 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! Objectoriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper
More informationAn 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 informationIntroduction 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 informationScheme. 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 firstclass values E.g., functions
More informationStructure 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 informationCS403: 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 informationFunctional Programming. Pure Functional Languages
Functional Programming Pure functional PLs Sexpressions cons, car, cdr Defining functions readevalprint loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure
More informationFunctional 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 informationCS3L 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 informationExercise 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