From 4eb5d80f9115578c63ce8360c240caaea2897e0c Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Thu, 1 Nov 2018 11:17:40 +0000 Subject: [PATCH] Add fold as an alias to mapBoth --- .../com/github/michaelbull/result/Map.kt | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/main/kotlin/com/github/michaelbull/result/Map.kt b/src/main/kotlin/com/github/michaelbull/result/Map.kt index b03d9a2..7c2d579 100644 --- a/src/main/kotlin/com/github/michaelbull/result/Map.kt +++ b/src/main/kotlin/com/github/michaelbull/result/Map.kt @@ -56,20 +56,43 @@ inline infix fun Result, E>.mapAll(transform: (V) -> Resul * - Elm: [Result.Extra.mapBoth](http://package.elm-lang.org/packages/elm-community/result-extra/2.2.0/Result-Extra#mapBoth) * - Haskell: [Data.Either.either](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:either) */ -inline fun Result.mapBoth(success: (V) -> U, failure: (E) -> U): U { +inline fun Result.mapBoth( + success: (V) -> U, + failure: (E) -> U +): U { return when (this) { is Ok -> success(value) is Err -> failure(error) } } +/** + * Maps this [Result][Result] to `U` by applying either the [success] function if this + * [Result] is [Ok], or the [failure] function if this [Result] is an [Err]. Both of these + * functions must return the same type (`U`). + * + * This is functionally equivalent to [mapBoth]. + * + * - Elm: [Result.Extra.mapBoth](http://package.elm-lang.org/packages/elm-community/result-extra/2.2.0/Result-Extra#mapBoth) + * - Haskell: [Data.Either.either](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:either) + */ +inline fun Result.fold( + success: (V) -> U, + failure: (E) -> U +): U { + return mapBoth(success, failure) +} + /** * Maps this [Result][Result] to [Result][Result] by applying either the [success] * function if this [Result] is [Ok], or the [failure] function if this [Result] is an [Err]. * * - Haskell: [Data.Bifunctor.Bimap](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Bifunctor.html#v:bimap) */ -inline fun Result.mapEither(success: (V) -> U, failure: (E) -> F): Result { +inline fun Result.mapEither( + success: (V) -> U, + failure: (E) -> F +): Result { return when (this) { is Ok -> Ok(success(value)) is Err -> Err(failure(error))