-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30thAug_higher_order_3
152 lines (99 loc) · 1.88 KB
/
30thAug_higher_order_3
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// passing funtions to functions
function f(h, x){
return h(x);
}
function g(y){
return y + 1;
}
f(g, 7);
// examples
// repeat_pattern
// transform_mosaic
function sum_integers(a, b){
return a > b
? 0
: a + sum_integers(a + 1, b);
}
sum_integers(4, 6);
// alternate cubes
function cube(x) {
return x * x * x;
}
function sum_skip_cubes(a, b){
return a > b
? 0
: cube(a) + sum_skip_cubes(a + 2, b);
}
sum_skip_cubes(1,5);
// abstraction cause very similar
/*
function sum(a, b){
return a > b ? 0
: (compute value with a)
+
sum((next value from a), b);
}
*/
function sum ( term , a , next , b ) {
return a > b ? 0
: term ( a )
+
sum ( term , next ( a ) , next , b );
}
/*
function plus_two(x){
return x + 2;
}
function sum_skip_cubes2(a, b){
return sum(cube, a, plus_two, b);
}
sum_skip_cubes2(1,5);
*/
// or
/*
function sum_skip_cubes2(a, b){
function cube(x) {
return x * x * x;
}
function plus_two(x){
return x + 2;
}
return sum(cube, a, plus_two, b);
}
makes the code neater
we dont need this functions outside anyway
*/
// (x1, x2) -> x1 + x2
// x1 -> x1 + 1
// alternate - arrow token
function sum_skip_cubes2(a, b){
return sum(x => x * x * x, a, x => x + 2, b);
}
sum_skip_cubes2(1,5);
// => another way to declare function
/*
function plus4(x) {
return x + 4;
}
can be written as:
*/
const plus4 = x => x + 4;
plus4(5);
function make_adder(x) {
/*
function adder(y) {
return x + y;
}
return adder;
*/
return y => x + y;
}
/*
const adder_four = make_adder(4);
adder_four(6);
*/
(make_adder(4))(6);
const adder_1 = make_adder(1);
const adder_2 = make_adder(2);
adder_1(10); // returns 11
adder_2(20) // returns 22