From c2fc72d0cbc4ba62585bf2eff064fde010dceb6f Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Thu, 11 Jan 2018 18:28:31 +0000 Subject: [PATCH] Add zip functions --- .../com/github/michaelbull/result/Zip.kt | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 src/main/kotlin/com/github/michaelbull/result/Zip.kt diff --git a/src/main/kotlin/com/github/michaelbull/result/Zip.kt b/src/main/kotlin/com/github/michaelbull/result/Zip.kt new file mode 100644 index 0000000..973d2cc --- /dev/null +++ b/src/main/kotlin/com/github/michaelbull/result/Zip.kt @@ -0,0 +1,93 @@ +package com.github.michaelbull.result + +private typealias Producer = () -> Result + +/** + * Apply a [transformation][transform] to two [Results][Result], if both [Results][Result] are [Ok]. + * If not, the first argument which is an [Err] will propagate through. + * + * - Elm: http://package.elm-lang.org/packages/elm-lang/core/latest/Result#map2 + */ +inline fun zip( + result1: Producer, + result2: Producer, + transform: (V1, V2) -> U +): Result { + return result1().flatMap { v1 -> + result2().map { v2 -> + transform(v1, v2) + } + } +} + +/** + * Apply a [transformation][transform] to three [Results][Result], if all [Results][Result] are [Ok]. + * If not, the first argument which is an [Err] will propagate through. + * + * - Elm: http://package.elm-lang.org/packages/elm-lang/core/latest/Result#map3 + */ +inline fun zip( + result1: Producer, + result2: Producer, + result3: Producer, + transform: (V1, V2, V3) -> U +): Result { + return result1().flatMap { v1 -> + result2().flatMap { v2 -> + result3().map { v3 -> + transform(v1, v2, v3) + } + } + } +} + +/** + * Apply a [transformation][transform] to four [Results][Result], if all [Results][Result] are [Ok]. + * If not, the first argument which is an [Err] will propagate through. + * + * - Elm: http://package.elm-lang.org/packages/elm-lang/core/latest/Result#map4 + */ +inline fun zip( + result1: Producer, + result2: Producer, + result3: Producer, + result4: Producer, + transform: (V1, V2, V3, V4) -> U +): Result { + return result1().flatMap { v1 -> + result2().flatMap { v2 -> + result3().flatMap { v3 -> + result4().map { v4 -> + transform(v1, v2, v3, v4) + } + } + } + } +} + +/** + * Apply a [transformation][transform] to five [Results][Result], if all [Results][Result] are [Ok]. + * If not, the first argument which is an [Err] will propagate through. + * + * - Elm: http://package.elm-lang.org/packages/elm-lang/core/latest/Result#map5 + */ +inline fun zip( + result1: Producer, + result2: Producer, + result3: Producer, + result4: Producer, + result5: Producer, + transform: (V1, V2, V3, V4, V5) -> U +): Result { + return result1().flatMap { v1 -> + result2().flatMap { v2 -> + result3().flatMap { v3 -> + result4().flatMap { v4 -> + result5().map { v5 -> + transform(v1, v2, v3, v4, v5) + } + } + } + } + } +}