package com.mikebull94.result inline fun Iterable.fold( initial: R, operation: (acc: R, T) -> Result ): Result { var accumulator = initial forEach { element -> val operationResult = operation(accumulator, element) when (operationResult) { is Ok -> { accumulator = operationResult.value } is Error -> return error(operationResult.error) } } return ok(accumulator) } inline fun List.foldRight(initial: R, operation: (T, acc: R) -> Result): Result { var accumulator = initial if (!isEmpty()) { val iterator = listIterator(size) while (iterator.hasPrevious()) { val operationResult = operation(iterator.previous(), accumulator) when (operationResult) { is Ok -> { accumulator = operationResult.value } is Error -> return error(operationResult.error) } } } return ok(accumulator) } /** * - Elm: [Result.Extra.combine](http://package.elm-lang.org/packages/circuithub/elm-result-extra/1.4.0/Result-Extra#combine) */ fun combine(vararg results: Result) = results.asIterable().combine() /** * - Elm: [Result.Extra.combine](http://package.elm-lang.org/packages/circuithub/elm-result-extra/1.4.0/Result-Extra#combine) */ fun Iterable>.combine(): Result, E> { return ok(map { when (it) { is Ok -> it.value is Error -> return error(it.error) } }) } /** * - Haskell: [Data.Either.lefts](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:lefts) */ fun getAll(vararg results: Result) = results.asIterable().getAll() /** * - Haskell: [Data.Either.lefts](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:lefts) */ fun Iterable>.getAll(): List { return filter { it is Ok }.map { (it as Ok).value } } /** * - Haskell: [Data.Either.rights](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:rights) */ fun getAllErrors(vararg results: Result) = results.asIterable().getAllErrors() /** * - Haskell: [Data.Either.rights](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:rights) */ fun Iterable>.getAllErrors(): List { return filter { it is Error }.map { (it as Error).error } } /** * - Haskell: [Data.Either.partitionEithers](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:partitionEithers) */ fun partition(vararg results: Result) = results.asIterable().partition() /** * - Haskell: [Data.Either.partitionEithers](https://hackage.haskell.org/package/base-4.10.0.0/docs/Data-Either.html#v:partitionEithers) */ fun Iterable>.partition(): Pair, List> { val values = mutableListOf() val errors = mutableListOf() forEach { result -> when (result) { is Ok -> values.add(result.value) is Error -> errors.add(result.error) } } return Pair(values, errors) }