Lecture L7 Updated - View
Lecture L7 Updated - View
State (3.1)
Sumobot Competition
15-Oct-2022, Saturday, 3pm-7pm, in COM1-SR1
Two competitions: Sumobot & Robot Talent Show
Studios have to sign up next week
Rules will be announced next week
State (3.1)
So far ...
Functional Programming
Example:
factorial(5) always gives 120
• No matter how many times you call it, or when you call it
State
function withdraw(amount) {
if (balance >= amount) {
balance = balance - amount;
return balance;
} else {
display("Insufficient funds");
return balance;
}
}
return withdraw;
}
const W1 = make_account(100);
W1(40); ➔ 60
W1(40); ➔ 20
W1(40); ➔ 20 "Insufficient funds"
function withdraw(amount) {
if (balance >= amount) {
return fn_make_account(balance - amount);
} else {
display("Insufficient funds");
return fn_make_account(balance);
}
}
return withdraw;
}
const W1 = fn_make_account(100);
const W2 = W1(40); ➔ fn_make_account(60)
const W3 = W2(40); ➔ fn_make_account(20)
const W4 = W3(40); ➔ fn_make_account(20) "Insufficient funds"
Assignment Statement
name = expression;
Example
balance; ➔ 100
balance; ➔ 80
balance; ➔ 60
Multiple Accounts
const W1 = make_account(100);
const W2 = make_account(100);
W1(50); ➔ 50
W2(70); ➔ 30
W2(40); ➔ 30 "Insufficient funds"
W1(40); ➔ 10
Assignment: Pros
Assignment: Cons
Consider
function make_simplified_withdraw(balance) {
return amount => {
balance = balance - amount;
return balance;
}
}
State (3.1)
Mutable Data
Mutable Pairs
set_head Example
Effect of set_head(x, y)
x c d x c d
a b a b
y e f y e f
set_tail Example
Effect of set_tail(x, y)
x c d x c d
a b a b
y e f y e f
Example:
const a = list(1, 3, 5);
const b = list(2, 4);
const c = append(a, b);
c; ➔ [1, [3, [5, [2, [4, null]]]]]
set_head(b, 9);
b; ➔ [9, [4, null]
c; ➔ [1, [3, [5, [9, [4, null]]]]]
a 1 3 5
b 2 4 pairs reused
c 1 3 5 new pairs
Before set_head(b, 9) a 1 3 5
b 2 4
c 1 3 5
After set_head(b, 9) a 1 3 5
b 9 4
c 1 3 5
Another example:
const a = list(1, 2, 3);
set_tail(tail(tail(a)), a);
Cyclical structure!
a 1 2 3
What is length(a)?!
Wanted:
A function to append two lists and return the result list
No new pair must be created
Result list is constructed from existing pairs of input lists
“Destructive” Append
Example:
const a = list(1, 3, 5); a 1 3 5
const b = list(2, 4);
b 2 4
b 2 4
“Destructive” Append
Implementation:
Show in
Playground
function d_append(xs, ys) {
if (is_null(xs)) {
return ys;
} else {
set_tail(xs, d_append(tail(xs), ys));
return xs;
}
}
xs 1 3 5
ys 2 4
“Destructive” Map
Example:
const a = list(1, 2, 3);
a 1 2 3
“Destructive” Map
Implementation:
Show in
Playground
function d_map(fun, xs) {
if (!is_null(xs)) {
set_head(xs, fun(head(xs)));
d_map(fun, tail(xs));
} else { }
}
xs 1 2 3