forked from joelvaneenwyk/language84
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.84
140 lines (115 loc) · 2.67 KB
/
list.84
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
{
: cons
: fold
: reduce
: for_each
: for_each_numbered
: iota
: map
: filter
: length
: reverse
: reverse_append
: append
: concat
: concat_map
: fetch
: zip
: unzip
: last
: join
: repeat
}
Where
Define (cons head tail)
[head & tail]
Define (map list transform)
(fold list 'nil Func {elem list} [(transform elem) & list])
Define (iota n)
Unfold i From 0
If [i = n]
'nil
[i & (Fold [i + 1])]
Define (filter list pred)
(fold list 'nil Func {elem list} If (pred elem) [elem & list] list)
Define (length list)
(reduce list 0
Func {count _} [count + 1])
Define (concat lists)
(fold lists 'nil append)
Define (concat_map list f)
(fold list 'nil
Func {item items} (append (f item) items))
Define (fetch list n)
If [n < 0]
'nothing
Iterate {list n}
Match list {
| 'cons.{item list}
If [n = 0]
'just.item
(Continue list [n - 1])
| 'nil 'nothing
}
Define (zip a b)
Iterate {a b z} From {a b 'nil}
Match a {
| 'cons.{ai a}
Match b {
| 'cons.{bi b} (Continue a b [{ai bi} & z])
| 'nil (reverse z)
}
| 'nil (reverse z)
}
Define (unzip list)
(fold list {'nil 'nil}
Func {{a b} {as bs}} {[a & as] [b & bs]})
Define (last items)
(reduce items 'nothing Func {_ item} 'just.item)
Define (join glue items)
(fold items 'nil
Func {item items}
Match items {
| 'nil [item & 'nil]
| 'cons._ [item & glue & items]
})
Define (repeat n elem)
Unfold n
If [n = 0] 'nil [elem & (Fold [n - 1])]
Where
Define (append left right) (reverse_append (reverse left) right)
Where
Define (reverse list) (reverse_append list 'nil)
Where
Define (reverse_append queue tail)
(reduce queue tail
Func {list elem} [elem & list])
Where
Define (fold list nil cons)
Unfold list
Match list {
| 'nil nil
| 'cons.{elem list} (cons elem (Fold list))
}
Define (reduce list zero plus)
Iterate {list sum} From {list zero}
Match list {
| 'nil sum
| 'cons.{elem list} (Continue list (plus sum elem))
}
Define (for_each list command)
Iterate list
Begin Match list {
| 'nil
| 'cons.{elem list}
(command elem)
(Continue list)
}
Define (for_each_numbered list command)
Iterate {i list} From {0 list}
Begin Match list {
| 'nil
| 'cons.{elem list}
(command i elem)
(Continue [i + 1] list)
}