Skip to content

Haskell

Michael Bull edited this page Mar 16, 2024 · 15 revisions

Mappings from Haskell's Either and Bifunctor types to kotlin-result.


<V, E, U> Result<V, E>.mapBoth(success: (V) -> U, failure: (E) -> U): U

If the value is Ok(V), apply the first function to V; if it is Err(E), apply the second function to E.

val value: String = Ok("he").mapBoth(
    success = { "$it succeeded" },
    failure = { "$it failed" }
)
// value = "he succeeded"

<V, E> Iterable<Result<V, E>>.getAll(): List<V>

Extracts from an Iterable of Result all the Ok elements. All the Ok elements are extracted in order.

val values: List<String> = getAll(
    Ok("hello"),
    Ok("world")
)
// values = [ "hello", "world" ]

<V, E> Iterable<Result<V, E>>.getAllErrors(): List<E>

Extracts from an Iterable of Result all the Err elements. All the Err elements are extracted in order.

val errors: List<String> = getAllErrors(
    Err("error 1"),
    Err("error 2")
)
// errors = [ "error 1", "error 2" ]

Return true if the result is a Ok, false otherwise.

val result = Ok(500)
if (result.isOk) {
    println("Result is ok")
}

Return true if the result is a Err, false otherwise.

val result = Err(600)
if (result.isErr) {
    println("Result is not ok")
}

<V, E> Result<V, E>.getOr(default: () -> V): V

Return the value of an Ok-result or a default value otherwise.

val value: String = Err("error").getOr { "default" }
// value = "default"

<V, E> Result<V, E>.getErrorOr(default: () -> E): E

Return the error of an Err-result or a default value otherwise.

val error: String = Ok("hello").getErrorOr { "world" }
// error = "world"

<V, E> Iterable<Result<V, E>>.partition(): Pair<List<V>, List<E>>

Partitions an Iterable of Result into a Pair of two Lists. All the Ok elements are extracted, in order, to the first value of the Pair. Similarly the Err elements are extracted to the second value of the Pair.

val pairs: Pair<List<String>, List<String>> = partition(
    Err("c#"),
    Ok("haskell"),
    Err("java"),
    Ok("f#"),
    Err("c"),
    Ok("elm"),
    Err("lua"),
    Ok("clojure"),
    Err("javascript")
)
// pairs.first = [ "haskell", "f#", "elm", "clojure" ]
// pairs.second = [ "c#", "java", "c", "lua", "javascript"]

<V, E, U, F> Result<V, E>.mapEither(success: (V) -> U, failure: (E) -> F): Result<U, F>

Map over both arguments at the same time.

val result: Result<String, String> = Err("the reckless").mapEither(
    success = { "the wild youth" },
    failure = { "the truth" }
)

// result = Err("the truth")
Clone this wiki locally