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
|
# File 'lib/jade/stdlib/result.rb', line 25
def code
<<~JADE
module Result exposing (
Result(..),
and_then,
from_maybe,
map,
map_error,
on_error,
sequence,
to_maybe,
with_default,
)
type Result(value, error)
= Ok(value)
| Err(error)
def map(result: Result(a, e), fn: a -> b) -> Result(b, e)
case result
in Ok(something)
something
|> fn
|> Ok
in Err(error) then Err(error)
end
end
def and_then(result: Result(a, e), fn: a -> Result(b, e)) -> Result(b, e)
case result
in Ok(something) then something |> fn
in Err(error) then Err(error)
end
end
def with_default(result: Result(a, e), default: a) -> a
case result
in Ok(something) then something
else default
end
end
def to_maybe(result: Result(a, e)) -> Maybe(a)
case result
in Ok(something) then Just(something)
else Nothing
end
end
def from_maybe(maybe: Maybe(a), error: e) -> Result(a, e)
case maybe
in Just(something) then Ok(something)
in Nothing then Err(error)
end
end
def map_error(result: Result(a, e), fn: e -> x) -> Result(a, x)
case result
in Err(error)
error
|> fn
|> Err
in Ok(something) then Ok(something)
end
end
def sequence(results: List(Result(a, e))) -> Result(List(a), e)
List.fold(
results,
Ok([]),
(acc, result) -> {
list <- acc
value <- result
Ok(list ++ [value])
},
)
end
def on_error(result: Result(a, e), fn: e -> Result(a, f)) -> Result(a, f)
case result
in Err(error) then error |> fn
in Ok(_) then result
end
end
implements Mappable(Result(a, e)) with
map: map
end
implements Chainable(Result(a, e)) with
and_then: and_then
end
JADE
end
|