@@ -64,20 +64,37 @@ func (r Result[T]) IsErr() bool {
64
64
return r .IsRight ()
65
65
}
66
66
67
- // Map applies a function to the success value if it exists.
67
+ // Map applies an endomorphic function to the success value if it exists.
68
+ //
69
+ // Deprecated: Use MapOk instead.
68
70
func (r Result [T ]) Map (f func (T ) T ) Result [T ] {
69
71
return Result [T ]{
70
72
MapLeft [T , error ](f )(r .Either ),
71
73
}
72
74
}
73
75
74
- // MapErr applies a function to the error value if it exists.
76
+ // MapOk applies an endomorphic function to the success value if it exists.
77
+ func (r Result [T ]) MapOk (f func (T ) T ) Result [T ] {
78
+ return Result [T ]{
79
+ MapLeft [T , error ](f )(r .Either ),
80
+ }
81
+ }
82
+
83
+ // MapErr applies an endomorphic function to the error value if it exists.
75
84
func (r Result [T ]) MapErr (f func (error ) error ) Result [T ] {
76
85
return Result [T ]{
77
86
MapRight [T ](f )(r .Either ),
78
87
}
79
88
}
80
89
90
+ // MapOk applies a non-endomorphic function to the success value if it exists
91
+ // and returns a Result of the new type.
92
+ func MapOk [A , B any ](f func (A ) B ) func (Result [A ]) Result [B ] {
93
+ return func (r Result [A ]) Result [B ] {
94
+ return Result [B ]{MapLeft [A , error ](f )(r .Either )}
95
+ }
96
+ }
97
+
81
98
// Option returns the success value as an Option.
82
99
//
83
100
// Deprecated: Use OkToSome instead.
@@ -137,8 +154,22 @@ func (r Result[T]) UnwrapOrFail(t *testing.T) T {
137
154
return r .left
138
155
}
139
156
140
- // FlatMap applies a function that returns a Result to the success value if it
141
- // exists.
157
+ // FlattenResult takes a nested Result and joins the two functor layers into
158
+ // one.
159
+ func FlattenResult [A any ](r Result [Result [A ]]) Result [A ] {
160
+ if r .IsErr () {
161
+ return Err [A ](r .right )
162
+ }
163
+
164
+ if r .left .IsErr () {
165
+ return Err [A ](r .left .right )
166
+ }
167
+
168
+ return r .left
169
+ }
170
+
171
+ // FlatMap applies a kleisli endomorphic function that returns a Result to the
172
+ // success value if it exists.
142
173
func (r Result [T ]) FlatMap (f func (T ) Result [T ]) Result [T ] {
143
174
if r .IsOk () {
144
175
return r
0 commit comments