blob: eee622651b990ec954a7f73bf49a9d649faa9e35 (
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
53
54
55
|
namespace;
include rt;
// closures: calls through values, shared captures, 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; };
rt.put_n(add(1)); rt.put_c(10);
rt.put_n(apply(add, 5)); rt.put_c(10);
let none = fn() { return 42; };
rt.put_n(none()); rt.put_c(10);
let n = 0;
let bump = fn(d) { n = n + d; return n; };
rt.put_n(bump(2)); rt.put_c(10);
rt.put_n(bump(5)); rt.put_c(10);
rt.put_n(n); rt.put_c(10);
let a = 2;
let outer = fn(x) {
let inner = fn(y) { return y + a + x; };
return inner(100);
};
rt.put_n(outer(7)); rt.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++; }
rt.put_n(s); rt.put_c(10);
let c = 3;
let plus = fn(v) { return v + c; };
rt.put_n(twice(plus, 1)); rt.put_c(10);
rt.put_n(sq(4)); rt.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++;
}
rt.put_n(total); rt.put_c(10);
let f = make(4);
rt.put_n(f(5)); rt.put_c(10);
let h = 1;
let frozen = fn(x) { return x + h; };
h = 100;
rt.put_n(frozen(1)); rt.put_c(10);
return 0;
}
|