-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.js
74 lines (63 loc) · 1.07 KB
/
list.js
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
// Creating the cons
function cons(x, xs = null) {
return i => {
if (i == 0) {
return x;
} else {
return xs;
}
};
}
// Constructing list functions
function lst() {
var args = Array.from(arguments);
if (args.length === 0) {
return null;
} else {
return cons(args[0], lst(...args.slice(1)));
}
}
function head(xs) {
return xs(0);
}
function tail(xs) {
return xs(1);
}
function isEmpty(xs) {
return xs == null;
}
function length(xs) {
if (isEmpty(xs)) {
return 0;
} else {
return 1 + length(tail(xs));
}
}
function concat(xs, ys) {
if (isEmpty(xs)) {
return ys;
} else {
return cons(head(xs), concat(tail(xs), ys));
}
}
function last(xs) {
if (isEmpty(tail(xs))) {
return head(xs);
} else {
return last(tail(xs));
}
}
function init(xs) {
if (isEmpty(tail(tail(xs)))) {
return cons(head(xs));
} else {
return cons(head(xs), init(tail(xs)));
}
}
function reverse(xs) {
if (isEmpty(xs)) {
return xs;
} else {
return concat(reverse(tail(xs)), cons(head(xs), null));
}
}