6.S050
Created: 2023-05-11 Thu 11:06
function fib(n) {
if (n == 0) { return 0; }
if (n == 1) { return 1; }
return fib(n - 1) + fib(n - 2);
}
function fib(n) {
if (n == 0) { return 0; }
if (n == 1) { return 1; }
return fib(n - 1) + fib(n - 2);
}
function fib_let(n) {
if (n == 0) { return 0; }
else if (n == 1) { return 1; }
else {
let a = fib_let(n - 1);
let b = fib_let(n - 2);
return a + b;
}
}
function fib_let(n) {
if (n == 0) { return 0; }
else if (n == 1) { return 1; }
else {
let a = fib_let(n - 1);
let b = fib_let(n - 2);
return a + b;
}
}
function fib_cps (n, k) {
if (n == 0) { k(0); }
else if (n == 1) { k(1); }
else {
fib_cps(n - 1, function(a) {
fib_cps(n - 2, function(b) {
k(a + b);
})
});
}
}
function fib_cps (n, k) {
if (n == 0) { k(0); }
else if (n == 1) { k(1); }
else {
fib_cps(n - 1, function(a) {
fib_cps(n - 2, function(b) {
k(a + b);
})
});
}
}
fib_cps(8, function(x) { console.log(x); });
21
while
and break
Evaluation relations:
break
to IMP
Evaluation relations:
break
to IMP
break
to IMP
goto
call/cc
call-with-current-continuation
or call/cc
call/cc
by example1 + (call/cc
(fun k -> 2 + (k 3))
call/cc
is a bit weird:
k
isn't really a function—it doesn't return!call/cc
is "unbounded": it captures the whole program as a continuation
What if we could capture only part of the continuation?
Enter shift
and reset
.
2 * (reset (1 + (shift k (k 5))))
What is k
here? The continuation up to the first reset
.
1 + []
So, computation is then:
2 * (1 + 5)
What about the following?
2 * (reset (1 + (shift k (k 5 + k 6))))
Can write the second rule as:
Say you're in the kitchen in front of the refrigerator, thinking about a sandwich. You take a continuation right there and stick it in your pocket. Then you get some turkey and bread out of the refrigerator and make yourself a sandwich, which is now sitting on the counter. You invoke the continuation in your pocket, and you find yourself standing in front of the refrigerator again, thinking about a sandwich. But fortunately, there's a sandwich on the counter, and all the materials used to make it are gone. So you eat it. :-)