Lecture 2026/01/27
Recall Memoization
Fib(100) runs in O(1.6^n) Time
(define fib-table empty)
(define memo-fib n )
(define res (assoc n fib-table))
(cond
[result => second]
[else
(define fib-n
(cond
[(<= n 1 ) n]
[else
(+ (memo-fib (- n 1))
(memo-fib (- n 1))
)]))))]
assoc- build-in functions for association list lookup(assoc x lst)returns the pair (x y ) from the list or falseAny value can be used as a test.
false is false.
anything else is true.
cond [x =>f]ifxis not false, then produce(f x), or else return false.
Claim: how does (memo-fib n) run oonly once.
fib-table is a global variable, this may result in dependencies from multiple parts of the program. Can we hide it? YES!
Doesn't quite work for the address work
Two functions need access to the global variable.
Exercise: Fix the issue with address-book
Mutations in C
Operator = performs mutation ( "assignment operator")
= is an operator.
x=y is an expression -> it has a vlaue as well as a n effect.
its value is the value assigned.
e.g. x=4 sets x to 4, and has value 4.
Advantages: - almost none
Disadvantages: - many
e.g.
x = y = z = 7; ,
z has value 7.
y has value 7.
Thus x has value 7.
x=4assigns x to 4, and since value is non-zero, that if-statement is true.always prints x is 4.
x=0assigns x to 0, since value is zero, that block never runs.
Easy to confuse assignment with equality check.
e.g.
if(x==4)...
if(x==0)...
Do Yoda Style to limit this.
(4 == x)since
(4=x)errors.
Usually best to use assignment only as a statement.
With this assignment operator, we can leave variables uninitalized and assign them later.
If x is used before it is initialized, what value is it?
Answer: Undefined behaviour (4B)
Thus it is not a good idea to just initialize a variable and not define it precisely, do so only with a very good reason.
e.g.
Will this run or not?
Answer: We don't fucking know.
The value of an uninitialized variable is undefined.
Typically it's whatever value was in the memory from before.
Global Variables
Be Careful (don't be cute lol):
printf("%d\n%d\n%d\n", f(), f(), f());
The order of argument evaluation is unspecified.
Avoid using expressions with side-effects as function arguments.
Because you don't know the order for which the functions are evaluated.
As with racket variables, can interfere with f by mutating c, in between function calls.
Can we protect c from access by functions other than f?
Yes.
A static variable is a global variable that only f can see.
local scope, but global extent.
Repetition:
Tail recursion is just repetition.
Expressed more idiomatically ( precise meaning? ) as
This repetition is conventionally represented by a loop.
The body of the loop is executed repeatedly, as long as the condition remains true.
In general:
becomes
May not need to be in its own function anymore, if its used only once !
Last updated