-
Notifications
You must be signed in to change notification settings - Fork 0
/
25thOct_advancedstreams
114 lines (77 loc) · 2.03 KB
/
25thOct_advancedstreams
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// seive of eratosthenes
function is_divisible(x, y){
return x % y === 0;
}
function seive(s){
return pair(head(s), () => seive(stream_filter(x => !is_divisible(x, head(s)), stream_tail(s))));
}
const primes = seive(integers_from(2));
// square roots by newton's method
/*
function improve(guess, x){
return average(guess, guess/x);
}
function sqrt_iter(guess, x){
if (good_enough(guess, x)){ // we dont know what good_enough is?
return guess;
}
else {
return sqrt_iter(improve(guess, x), x);
}
}
function sqrt(x) {
return sqrt_iter(1.0, x);
}
*/
// using streams for iteration
function average(a,b){
return (a + b)/2;
}
function improve(guess, x){
return average(guess, x/guess);
}
function sqrt_stream(x){
const guesses = pair(1.0, () => stream_map(guess => improve(guess, x), guesses));
return guesses;
}
eval_stream(sqrt_stream(4), 6);
// approximating pi
// pi/4 = 1 - 1/3 + 1/5 - 1/7 ...
// function to produce a stream of summands
// i.e. 1, -1/3, 1/5...
function pi_summands(n) {
return pair(1 / n,
() => stream_map(x => -x, pi_summands(n + 2)));
}
eval_stream(pi_summands(1), 10);
function add_streams(s1, s2) {
return is_null(s1)
? s2
: is_null(s2)
? s1
: pair(head(s1) + head(s2),
() => add_streams(stream_tail(s1),
stream_tail(s2)));
}
// Returns a stream whose elements are
// s0, s0 + s1, s0 + s1 + s2, ...
function partial_sums(s) {
return pair(head(s), () => add_streams(partial_sums(s), stream_tail(s)));
}
// similar to fibonacci
function scale_stream(s, f) {
return stream_map(x => x * f, s);
} // multiply by 4 cause we find for pi/4
const pi_stream =
scale_stream(partial_sums(pi_summands(1)), 4);
eval_stream(pi_stream, 8);
//should return:
// [4,
// [2.666666666666667,
// [3.466666666666667,
// [2.8952380952380956,
// [3.3396825396825403,
// [2.9760461760461765,
// [3.2837384837384844,
// [3.017071817071818,
// null]]]]]]]]