blob: 660c32a195a07e322d2df34111f8ae190123b39e (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
// closures: calls through values, captures by value, state in a capture,
// nested captures, closures passed as arguments and returned from functions
fn apply(f, x) { return f(x); }
fn twice(g, x) { return g(g(x)); }
fn sq(x) { return x * x; }
word.u make(n) {
let h = fn(x) { return x * n; };
return u*h;
}
fn main() {
let k = 10, m = 3;
let add = fn(x) { return x + k * m; };
put_n(add(1)); put_c(10);
put_n(apply(add, 5)); put_c(10);
let none = fn() { return 42; };
put_n(none()); put_c(10);
let n = 0;
let bump = fn(d) { n = n + d; return n; };
put_n(bump(2)); put_c(10);
put_n(bump(5)); put_c(10);
put_n(n); put_c(10);
let a = 2;
let outer = fn(x) {
let inner = fn(y) { return y + a + x; };
return inner(100);
};
put_n(outer(7)); put_c(10);
let base = 5;
let scale = fn(i) { return i * base; };
let s = 0, i = 0;
while (i < 4) { s = s + scale(i); i++; }
put_n(s); put_c(10);
let c = 3;
let plus = fn(v) { return v + c; };
put_n(twice(plus, 1)); put_c(10);
put_n(sq(4)); put_c(10);
let total = 0, j = 0;
while (j < 3) {
let kk = j;
let g = fn(x) { return x + kk; };
total = total + g(10);
j++;
}
put_n(total); put_c(10);
let f = make(4);
put_n(f(5)); put_c(10);
let h = 1;
let frozen = fn(x) { return x + h; };
h = 100;
put_n(frozen(1)); put_c(10);
return 0;
}
|