2017-10-21 02:51:30 +00:00
|
|
|
package com.mikebull94.result
|
|
|
|
|
|
|
|
/**
|
|
|
|
* - Elm: [Result.map](http://package.elm-lang.org/packages/elm-lang/core/latest/Result#map)
|
|
|
|
* - Haskell: [Data.Bifunctor.first](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Bifunctor.html#v:first)
|
2017-10-21 15:52:29 +00:00
|
|
|
* - Rust: [Result.map](https://doc.rust-lang.org/std/result/enum.Result.html#method.map)
|
2017-10-21 02:51:30 +00:00
|
|
|
*/
|
2017-10-21 15:52:29 +00:00
|
|
|
infix inline fun <V, E, U> Result<V, E>.map(transform: (V) -> U): Result<U, E> {
|
2017-10-21 02:51:30 +00:00
|
|
|
return when (this) {
|
|
|
|
is Ok -> ok(transform(value))
|
2017-10-21 14:03:39 +00:00
|
|
|
is Error -> err(error)
|
2017-10-21 02:51:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* - Elm: [Result.mapError](http://package.elm-lang.org/packages/elm-lang/core/latest/Result#mapError)
|
|
|
|
* - Haskell: [Data.Bifunctor.right](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Bifunctor.html#v:second)
|
2017-10-21 15:52:29 +00:00
|
|
|
* - Rust: [Result.map_err](https://doc.rust-lang.org/std/result/enum.Result.html#method.map_err)
|
2017-10-21 02:51:30 +00:00
|
|
|
*/
|
2017-10-21 17:52:14 +00:00
|
|
|
infix inline fun <V, E, F> Result<V, E>.mapError(transform: (E) -> F): Result<V, F> {
|
2017-10-21 02:51:30 +00:00
|
|
|
return when (this) {
|
|
|
|
is Ok -> ok(value)
|
2017-10-21 14:03:39 +00:00
|
|
|
is Error -> err(transform(error))
|
2017-10-21 02:51:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* - Elm: [Result.Extra.mapBoth](http://package.elm-lang.org/packages/circuithub/elm-result-extra/1.4.0/Result-Extra#mapBoth)
|
|
|
|
* - Haskell: [Data.Either.either](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:either)
|
|
|
|
*/
|
2017-10-21 03:21:56 +00:00
|
|
|
inline fun <V, E, U> Result<V, E>.mapBoth(
|
|
|
|
success: (V) -> U,
|
|
|
|
failure: (E) -> U
|
|
|
|
): U {
|
2017-10-21 02:51:30 +00:00
|
|
|
return when (this) {
|
|
|
|
is Ok -> success(value)
|
|
|
|
is Error -> failure(error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: better name?
|
|
|
|
/**
|
|
|
|
* - Haskell: [Data.Bifunctor.Bimap](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Bifunctor.html#v:bimap)
|
|
|
|
*/
|
|
|
|
inline fun <V1, V2, E1, E2> Result<V1, E1>.mapEither(
|
2017-10-21 03:21:56 +00:00
|
|
|
success: (V1) -> V2,
|
|
|
|
failure: (E1) -> E2
|
2017-10-21 02:51:30 +00:00
|
|
|
): Result<V2, E2> {
|
|
|
|
return when (this) {
|
2017-10-21 03:21:56 +00:00
|
|
|
is Ok -> ok(success(value))
|
2017-10-21 14:03:39 +00:00
|
|
|
is Error -> err(failure(error))
|
2017-10-21 02:51:30 +00:00
|
|
|
}
|
|
|
|
}
|