# Lecture: Modeling State with Assignment and Streams

### Background Material

• Bound and free variables and scope rules (see chapter 3 of the text)
• Review evaluation rules of scheme (see introduction to scheme)

• Chapters 10 of the text and Sections (1.1.5, 3.1, 3.2, 3.5 of SICP)

### Theme

Assignment allows a program to update a variable and hence model the state of an object through changes in the variable. As we will see, in lambda calculus lecture technically not having assignment does not limit what can be computed; however, using assignment as indicated above does make it easier to write programs that model state. The disadvantage of allowing assignment is that the semantics of the resulting programs are much harder to understand and describe.

In this lecture we will illustrate how to use assignment in scheme and to use assignment along with local variables to produce functions that model the state of an object. We will also investigate that the simple semantics that work for pure functional languages does not work when assignment is allowed and will review the environment model that does allow assignment.

After discussing the benefits and costs of assignment, we will introduce another computational model, streams, that can be used to model state but does not require assignment. Streams, sequences of data - potentially infinite, and stream processing provides a useful abstraction for many computational problems. We will illustrate stream processing, discuss a clever technique for implementing streams that make them much more efficient, and see how they can be used to model state.

### Topics

1. Modeling state with assignment in scheme (SICP sec. 3.1.1)
• Modeling a bank account - function to create an account (withdraw, deposit) with an initial deposit. Returns functions to withdraw and deposit using a local variable to keep track of the balance.
2. Substitution model for function evaluation (SICP sec. 1.1.5, Louden sec. 11.8)
• Applicative order evaluation
• Normal order evaluation
• Nonstrict vs. strict functions - order can make a difference.
• Church-Rosser theorem
3. Cost of assignment (SICP sec. 3.1.3)
• Failure of the substitution model
• Referential transparency
• Sameness and change
4. Environment model for function evaluation (SICP sec. 3.2, Louden sec. 13.2)
• procedure definition and application
• lexical scope and local variables
5. Stream processing (SICP sec. 3.5, Louden sec. 11.5)
• Stream Processing
• Delayed evaluation and implementation of streams
• Modeling state with streams

### Sample Functions

• ch3.scm - chapter 3 functions from SICP.

### Exercises

• Trace some simple examples of the substitution model using both applicative and normal order evaluation.
• Trace environment model on some simple examples.
• Trace withdraw and stream examples.
Created: Apr. 10, 2007 (revised April 5, 2012) by jjohnson AT cs DOT drexel DOT DOT edu