-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path25Oct_Streams2_memoize
87 lines (65 loc) · 1.88 KB
/
25Oct_Streams2_memoize
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// functions often have an effect beyond the value they are computing
// when we talk about lazy evaluation, these effects are called side effects
// pure functional programming : programming without side effects
// all values can be memoized
// results not affected my memoization
function memo_fun(fun) {
display(fun);
display("hi");
let already_run = false;
let result = undefined;
function mfun() {
if (!already_run) {
result = fun();
already_run = true;
display(result);
return result;
} else {
display("result");
return result;
}
}
return mfun;
}
function ms(m, s) {
display(m);
return s;
}
//const ones = pair(1, () => ones);
//const onesA = pair(1, () => ms("A", onesA));
//const onesB = pair(1, memo_fun(() => ms("B", onesB)));
//const onesC = pair(1, memo_fun(() => onesC));
//stream_ref(ones, 3);
//stream_ref(onesA, 3);
//stream_ref(onesB, 3);
//stream_ref(onesC,3);
// example 2
function m_integers_from(n) {
return pair(n,
memo_fun(() => ms("M: " + stringify(n),
m_integers_from(n + 1))));
}
function integers_from(n) {
return pair(n,
() => ms("M: " + stringify(n),
integers_from(n + 1)));
}
const m_integers = m_integers_from(1);
/*
stream_ref(m_integers, 0);
stream_ref(m_integers, 1);
stream_ref(m_integers, 2);
stream_ref(m_integers, 5);
stream_ref(m_integers, 5);
const integers = integers_from(1);
stream_ref(integers, 0);
stream_ref(integers, 1);
stream_ref(integers, 2);
*/
// basically here the result of memoized stores the previous computation
// so now we only have to calculate new one
stream_ref(m_integers, 0);
stream_ref(m_integers, 1);
stream_ref(m_integers, 5);
// that is why 1 2 3 4 5 and then 1 1 2 3 4 5
// cause 1's computation is already stored