Comp210 Lecture # 32    Fall 2002

(today's code)

set!

Consider:

(random 10)
(random 10)
(random 10)
What's going on? This "function" has some hidden state! Or, consider the phone company, adding new numbers:
(lookup 'presley)
= false

(add-entry! 'presley 8675309)

(lookup 'presley)
= 8675309
In this latter case, presumably there is a placeholder directory which is sitting around, and the list bound to directory changes over time -- a variable. How can we get our functions to do this? It could certainly be fudged by using set-struct-field!, with a bit of work; but it can also be done a bit more directly, with a new piece of syntax.

Changing a binding is the work of set!.

(define speed-limit 75)
(define scofflaw-margin 1.1)
(define my-cruising-speed (* scofflaw-margin speed-limit))

my-cruising-speed = 82.5


(set! speed-limit 55)

speed-limit = 55
my-cruising-speed = 82.5
(If we'd really wanted my-cruising-speed to depend on the speed-limit, we should make it a function.)

set! is not set-struct-field!

(define a (+ 2 3))
(define b a)
(set! a 'volkswagen)
b

(define aa (make-posn 2 3))
(define bb aa)
(set-posn-x! aa 99)
bb
Similarly, if you call translate-posn! on bb, both aa and bb can notice a change. But:
(define (silly x)
  (begin (set! x 17)    ; Not actually legal in Advanced, but if it were...
         'done))

aa
(silly aa)
aa
bb
The only way for aa to get a new value is by evaluating (set! aa ...); similarly/separately for bb. (Note that the placeholders a,b don't get new values; just, the structure they refer to is modified.)

This is called "pass-by-value". When calling a function, the arguments (values) are copied onto a piece of paper, and handed to the function; even if re-writing on those pieces of paper, the function can't re-write the caller's data (if it's not in scope).

Using set-first! and set-rest!, could you write a function

;; remove!: any, list --> (void)
;;   Modify the list "items" so that
;;   it no longer contains any occurrence of target.
;;   
(define (remove! target items)
  ...)
What if items contained only target? (To really do this, you'd need a structure containing a list!)


Got to here during class, after finishing the depth-first-search-with-marking from last week.

Another example:
A random-number generator:

(define seed 0)
;; return a pseudo-random int in [0,100)
(define (rand)
  (begin (set! seed (next-num seed))
         seed))

;; next-num: number --> number
;; Return the next number in an (ahem) random sequence.
;;
(define (next-num n)
  (remainder (+ 17 (* n 41)) 100))
Calling (rand) repeatedly yields: This yields the sequence 17, 14, 91, 48, 85, ...
Must this repeat? A bit of thinking shows that it must, with a cycle of length 100 (or possibly less?). (NB if i change 41 to 43, i get 17,48,81,0,17,... -- oops, repeating very soon!)

Of course, the limit 100 could be made more flexible: How could we make it so ? (define max-rand 100)


Sharing state between several functions:
;;;;;;;;;;;;;;;;;;;
(define directory empty)

(define-struct entry (name number))

;; add-entry!: symbol number --> list-of-entries
;; SIDE-EFFECT: add a new entry to direcotry.
;; We return (the updated) directory.
;;   (Not necessary to return this, since anybody can
;;   look up the placeholder "directory" at any time,
;;   to get that same info.)
;;
;;   However, a useful rule of thumb: when writing a function
;;   which modifies an object but doesn't otherwise return
;;   an interesting value, have it return the object being modified.
;;   This is often convenient in allowing you to pass that
;;   value to the next function, w/o having to use "begin".
;;
(define (add-entry! name number)
  (begin
    (set! directory (cons (make-entry name number) directory))
    directory))

;; lookup: symbol --> entry or false
;;
(define (lookup name)
  (lookup-helper name directory))

;; lookup-helper: symbol, list-of-entries --> entry or false
;;
(define (lookup-helper name entries)
  (cond [(empty? entries) false]
        [(cons?  entries) (if (symbol=? (entry-name (first entries)) name)
                              (first entries)
                              (lookup-helper name (rest entries)))]))
There is one big problem with this: the directory is public to everybody, and other programmers might (inadvertently) change the directory directly. And perhaps incorrectly, even if they're smart people: maybe your add-entry! prohibits duplicate entries, and your lookup relies on this fact, but somebody else didn't realize this and bypassed your add-entry!!

(b) An alternative use: keep track of history. You are disgruntled, about to quit, and you write code that will stop working after 100 times (just returning 'haha instead of answer). Version I:

  (define times-called 0)
  (define select-by-color
    (lambda (kroma)
       (begin (set! times-called (add1 times-called))
              (if (> times-called 100)
                  'haha
                  ...the real code...))))


Version II: We don't want the placeholder to be global. Move it inside the define, before the lambda.
Question: does this make a new copy of the placeholder every time select-by-color is called? Or just one placeholder? (Clearly, we want the latter.)

To answer, remember the law-of-scheme, the semantics of "define". In particular, Cf. (define x (+ 3 4)) Is + called every time x is used, or just once? Answer: The way define works, just once. Here, "local" is analagous to "+". It is only evaluated once, creates a placeholder with a name inaccessible anywhere else (say, times-called%473), and then it returns a value (a function which includes times-called%473 in its closure).

What if we'd put the local inside the lambda? Then every time we call the function, the local is evaluated, making a new placeholder every single time, and each function has a different times-called%xxx in its closure. Cf. (define function-x (lambda () (+ 3 4))) Now, every time function-x is called, the + is evaluted.


When is an example when we might want indeed to have the local be inside the lambda, to create a local var many times? Probably when the value returned is a function and each function returned wants to use its own local variable (alternative: all functions returned refer to the same variable.) What is wrong with the following?

;; make-shopper-card: name --> (command, any --> any)
;;
(define make-shopper-card
  (local [(define most-recently-bought #f)]
    (lambda (name)
       (lambda (command some-item)
          (cond [(eq? command 'show-name) name]
                [(eq? command 'buy) (set! most-recently-bought some-item)]
                [(eq? command 'show-fave) most-recently-bought])))))
How to fix it?


(c) Imperative programming:
In scheme, the fundamental unit of computation is function-call. (A functional language)
In imperative langauges (Java, C, assembly), the fundamental unit is assign-to-variable (set!) and sequencing (begin), with a lesser emphasis on calling functions. (This functional/imperative classification is independent of whether or not a language is object-oriented.)


Summary: Pragmatics of set!

(These following uses are not always clean-cut; e.g. keeping track of history is one common example of keeping state.)

When using set!, you might want to reflect on which of these purposes you're using it for. And if not any of these, you might want to reflect on whether your program needs set!, and if the structure of the code might better match the structure of the data if you use one of the templates (structure, w/ accumulator, generative). Don't forget everything you've learned previously!

 

©2002 Ian Barland