Lecture 2026-01-29

Accumulators

int f (int c, int acc){
if(cont(c)){
body(c);
return f(update1(c), update2(acc,c));
}
return g(acc)
}
f(c,acc,0)

This implies,

int acc = acc0;
while (cont(c)){
body(c);
acc= update2(acc,c);
c=update1(c);
}
acc= g(acc);

For example:

circle-info

Common emerges ( initalize variables )

e.g.

Alternate Format

or e.g.

or even,

Or even,

circle-info

You don't have to have a block inside for a for loop

Peekchar version:

or

Updating Counters

circle-info

Very common patterns one might do in a loop.

Specialized Syntax

circle-info

equivalent to previous

Incrementing decreasing by 1.

circle-info

These are expressions - have a value as well as an effect

++c increments c c + produces the value of c

--i decrements i + produces the value of i.

But an unintuitive leading question would be: Which Value?

  • Which value of c , or i?

  • The old value or the new one?

To find out:

circle-info

There are also postfix versions: c++, i--

  • Give value before effect.

  • Increment/decrement i, but produces the old value of i.

    • But this implies that the old vale must be remembered or recomputed?

      • This is some weird behaviour !

circle-info

If you use increment/decrement, perfer the prefix version.

More on Global Data:

  • global variables:

circle-info

Global Constants are still useful !

  • Can force a variable to remain contant in C.

e.g.

Intermediate Mutation ( Racket )

  • What if we want to work with multiple address books?

  • No Change is Made to Home.

    • Code doesn't work,

    • Not Clear how to make it work.

      • Why?

Substitution Model

circle-info

Do you see how this doesn't work? The home address-book is lost !

To make this work...

  • Recall from CS145 (??)

    • simulation of structs using lambda

  • Do the same thing to create a structure with one field - called a box.

    • Two operations

      • get the value in the box.

      • set the value to a new value.

e.g.

  • The box is not v itself, its an agent that can, on demand, produce v or 7.

To support set

  • We must introduce a local copy of v ( why? )

circle-info

Adding set requires an extra parameter

  • Achieve by having the box return a function

circle-info

The box is not a value, its the in between agent that gets the value.

  • Next steps, using stepping rules to ensure the value actually sets the value.

Last updated