-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata-either.red
71 lines (63 loc) · 2.02 KB
/
data-either.red
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
Red [
Title: "Data.Either"
Author: "unchartedworks"
File: %data-either.red
Tabs: 4
Rights: "unchartedworks. All rights reserved."
License: "MIT"
]
Left: [x] -> [make object! [type: 'Left value: x]]
Right: [x] -> [make object! [type: 'Right value: x]]
either': [
"Case analysis for the Either type. If the value is Left a, apply the first function to a; if it is Right b, apply the second function to b."
f [any-function!]
g [any-function!]
mx [object!]
] -> [
case [
(isLeft mx) (f fromLeft)
(isRight mx) (f fromRight)
otherwise (cause-error 'script 'invalid-arg [mx])
]
]
isLeft: [
"Return True if the given value is a Left-value, False otherwise."
x [object!]
] -> [x/type == 'Left]
isRight: [
"Return True if the given value is a Right-value, False otherwise."
x [object!]
] -> [x/type == 'Right]
fromLeft: [
"Return the contents of a Left-value or a default value otherwise."
mx [object!]
] -> [
either (isLeft mx) [mx/value] [cause-error 'script 'invalid-arg [mx]]
]
fromRight: [
"Return the contents of a Right-value or a default value otherwise."
mx [object!]
] -> [
either (isRight mx) [mx/value] [cause-error 'script 'invalid-arg [mx]]
]
partitionEithers: [
"Partitions a list of Either into two lists. All the Left elements are extracted, in order, to the first component of the output. Similarly the Right elements are extracted to the second component of the output."
mxs' [series!]
] -> [
mxs: reduce mxs'
xs: reduce [map :fromLeft (filter :isLeft mxs)]
ys: reduce [map :fromRight (filter :isRight mxs)]
reduce xs ++ ys
]
either': function [
"Case analysis for the Either type. If the value is Left a, apply the first function to a; if it is Right b, apply the second function to b."
f [any-function!]
g [any-function!]
mx [object!]
][
case [
(isLeft mx) (f (fromLeft mx))
(isRight mx) (g (fromRight mx))
otherwise (cause-error 'script 'invalid-arg [mx])
]
]