forked from pen-lang/pen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
List.pen
66 lines (60 loc) · 1.34 KB
/
List.pen
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
# This module provides common list operations.
# Get the first element in a list. If a list is empty, it returns a fallback value.
First = \(xs [any], fallback any) any {
if [x, ..._] = xs {
x()
} else {
fallback
}
}
# Get the last element in a list. If a list is empty, it returns a fallback value.
Last = \(xs [any], fallback any) any {
if [x, ...xs] = xs {
last(xs, x)
} else {
fallback
}
}
last = \(xs [any], x \() any) any {
if [x, ...xs] = xs {
last(xs, x)
} else {
x()
}
}
# Convert a list of an `any` type to one of a `number` type skipping non-`number` types.
ToNumbers = \(xs [any]) [number] {
if [x, ...xs] = xs {
if x = x() as number {
[number x, ...ToNumbers(xs)]
} else {
ToNumbers(xs)
}
} else {
[number]
}
}
# Convert a list of an `any` type to one of a `string` type skipping non-`string` types.
ToStrings = \(xs [any]) [string] {
if [x, ...xs] = xs {
if x = x() as string {
[string x, ...ToStrings(xs)]
} else {
ToStrings(xs)
}
} else {
[string]
}
}
# Convert a list of an `any` type to one of a `boolean` type skipping non-`boolean` types.
ToBooleans = \(xs [any]) [boolean] {
if [x, ...xs] = xs {
if x = x() as boolean {
[boolean x, ...ToBooleans(xs)]
} else {
ToBooleans(xs)
}
} else {
[boolean]
}
}