Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Arrow Core & Fx syntax for Kotlin's Result type #2478

Merged
merged 9 commits into from
Sep 8, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ import io.kotest.property.arbitrary.of
import io.kotest.property.arbitrary.orNull
import io.kotest.property.arbitrary.short
import io.kotest.property.arbitrary.string
import kotlin.Result.Companion.failure
import kotlin.Result.Companion.success
import kotlin.jvm.JvmOverloads
import kotlin.math.abs
import kotlin.random.nextInt
Expand All @@ -62,6 +64,9 @@ public fun <A> Arb.Companion.functionToA(arb: Arb<A>): Arb<() -> A> =
public fun Arb.Companion.throwable(): Arb<Throwable> =
Arb.of(listOf(RuntimeException(), NoSuchElementException(), IllegalArgumentException()))

public fun <A> Arb.Companion.result(arbA: Arb<A>): Arb<Result<A>> =
Arb.choice(arbA.map(::success), throwable().map(::failure))

public fun Arb.Companion.doubleSmall(): Arb<Double> =
Arb.numericDoubles(from = 0.0, to = 100.0)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package arrow.core.test.generators

import kotlin.coroutines.Continuation
import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED
import kotlin.coroutines.intrinsics.intercepted
import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn
import kotlin.coroutines.startCoroutine
import kotlinx.coroutines.Dispatchers

public suspend fun Throwable.suspend(): Nothing =
suspendCoroutineUninterceptedOrReturn { cont ->
suspend { throw this }.startCoroutine(
Continuation(Dispatchers.Default) {
cont.intercepted().resumeWith(it)
}
)

COROUTINE_SUSPENDED
}

public suspend fun <A> A.suspend(): A =
nomisRev marked this conversation as resolved.
Show resolved Hide resolved
suspendCoroutineUninterceptedOrReturn { cont ->
suspend { this }.startCoroutine(
Continuation(Dispatchers.Default) {
cont.intercepted().resumeWith(it)
}
)

COROUTINE_SUSPENDED
}
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,21 @@ public inline fun <E, A, B> Iterable<A>.traverseEither(f: (A) -> Either<E, B>):
public fun <E, A> Iterable<Either<E, A>>.sequenceEither(): Either<E, List<A>> =
traverseEither(::identity)

public inline fun <A, B> Iterable<A>.traverseResult(f: (A) -> Result<B>): Result<List<B>> {
val acc = mutableListOf<B>()
forEach { a ->
val res = f(a)
res.fold(
{ acc.add(it) },
{ return@traverseResult Result.failure(it) }
)
}
return Result.success(acc)
nomisRev marked this conversation as resolved.
Show resolved Hide resolved
}

public fun <A> Iterable<Result<A>>.sequenceResult(): Result<List<A>> =
traverseResult(::identity)

public inline fun <E, A, B> Iterable<A>.traverseValidated(
semigroup: Semigroup<E>,
f: (A) -> Validated<E, B>
Expand Down
211 changes: 211 additions & 0 deletions arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/Result.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
package arrow.core

import kotlin.Result.Companion.failure
import kotlin.Result.Companion.success

@PublishedApi
internal inline val unitResult: Result<Unit>
nomisRev marked this conversation as resolved.
Show resolved Hide resolved
inline get() = success(Unit)

public inline fun <A, B> Result<A>.flatMap(transform: (value: A) -> Result<B>): Result<B> =
fold({ a ->
try {
transform(a)
} catch (e: Throwable) {
failure(e)
}
}) { throwable ->
failure(throwable)
}
nomisRev marked this conversation as resolved.
Show resolved Hide resolved

public inline fun <A> Result<A>.handleErrorWith(transform: (throwable: Throwable) -> Result<A>): Result<A> =
nomisRev marked this conversation as resolved.
Show resolved Hide resolved
fold({ a -> success(a) }) { throwable ->
try {
transform(throwable)
} catch (e: Throwable) {
failure(e)
}
}

public inline fun <A, B> Result<A>.redeemWith(
handleErrorWith: (throwable: Throwable) -> Result<B>,
transform: (value: A) -> Result<B>
): Result<B> =
fold({ a ->
try {
transform(a)
} catch (e: Throwable) {
failure(e)
}
}) { throwable ->
try {
handleErrorWith(throwable)
} catch (e: Throwable) {
failure(e)
}
}

public inline fun <A, B, C> Result<A>.zip(b: Result<B>, map: (A, B) -> C): Result<C> =
zip(
b,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult
) { a, b, _, _, _, _, _, _, _, _ -> map(a, b) }

public inline fun <A, B, C, D> Result<A>.zip(b: Result<B>, c: Result<C>, map: (A, B, C) -> D): Result<D> =
zip(
b,
c,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult
) { a, b, c, _, _, _, _, _, _, _ -> map(a, b, c) }

public inline fun <A, B, C, D, E> Result<A>.zip(
b: Result<B>,
c: Result<C>,
d: Result<D>,
map: (A, B, C, D) -> E
): Result<E> =
zip(
b,
c,
d,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult,
unitResult
) { a, b, c, d, _, _, _, _, _, _ -> map(a, b, c, d) }

public inline fun <A, B, C, D, E, F> Result<A>.zip(
b: Result<B>,
c: Result<C>,
d: Result<D>,
e: Result<E>,
map: (A, B, C, D, E) -> F
): Result<F> =
zip(b, c, d, e, unitResult, unitResult, unitResult, unitResult, unitResult) { a, b, c, d, e, f, _, _, _, _ ->
map(
a,
b,
c,
d,
e
)
}

public inline fun <A, B, C, D, E, F, G> Result<A>.zip(
b: Result<B>,
c: Result<C>,
d: Result<D>,
e: Result<E>,
f: Result<F>,
map: (A, B, C, D, E, F) -> G
): Result<G> =
zip(b, c, d, e, f, unitResult, unitResult, unitResult, unitResult) { a, b, c, d, e, f, _, _, _, _ ->
map(
a,
b,
c,
d,
e,
f
)
}

public inline fun <A, B, C, D, E, F, G, H> Result<A>.zip(
b: Result<B>,
c: Result<C>,
d: Result<D>,
e: Result<E>,
f: Result<F>,
g: Result<G>,
map: (A, B, C, D, E, F, G) -> H
): Result<H> =
zip(b, c, d, e, f, g, unitResult, unitResult, unitResult) { a, b, c, d, e, f, g, _, _, _ -> map(a, b, c, d, e, f, g) }

public inline fun <A, B, C, D, E, F, G, H, I> Result<A>.zip(
b: Result<B>,
c: Result<C>,
d: Result<D>,
e: Result<E>,
f: Result<F>,
g: Result<G>,
h: Result<H>,
map: (A, B, C, D, E, F, G, H) -> I
): Result<I> =
zip(b, c, d, e, f, g, h, unitResult, unitResult) { a, b, c, d, e, f, g, h, _, _ -> map(a, b, c, d, e, f, g, h) }

public inline fun <A, B, C, D, E, F, G, H, I, J> Result<A>.zip(
b: Result<B>,
c: Result<C>,
d: Result<D>,
e: Result<E>,
f: Result<F>,
g: Result<G>,
h: Result<H>,
i: Result<I>,
map: (A, B, C, D, E, F, G, H, I) -> J
): Result<J> =
zip(b, c, d, e, f, g, h, i, unitResult) { a, b, c, d, e, f, g, h, i, _ -> map(a, b, c, d, e, f, g, h, i) }

public inline fun <A, B, C, D, E, F, G, H, I, J, K> Result<A>.zip(
b: Result<B>,
c: Result<C>,
d: Result<D>,
e: Result<E>,
f: Result<F>,
g: Result<G>,
h: Result<H>,
i: Result<I>,
j: Result<J>,
map: (A, B, C, D, E, F, G, H, I, J) -> K
): Result<K> = Nullable.zip(
getOrNull(),
b.getOrNull(),
c.getOrNull(),
d.getOrNull(),
e.getOrNull(),
f.getOrNull(),
g.getOrNull(),
h.getOrNull(),
i.getOrNull(),
j.getOrNull(),
map
)?.let { success(it) } ?: composeErrors(
exceptionOrNull(),
b.exceptionOrNull(),
c.exceptionOrNull(),
d.exceptionOrNull(),
e.exceptionOrNull(),
f.exceptionOrNull(),
g.exceptionOrNull(),
h.exceptionOrNull(),
i.exceptionOrNull(),
j.exceptionOrNull(),
)!!.let(::failure)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had a random thought, not blocking of course. I was wondering if it would make it easier to read these zip implementations if we use computations instead of delegate to higher arity functions,

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I choose the most effiecient implementation that was still somewhat readablee and short here. Writing this as a nullable { } will suffer from the same problem. The only way to write this properly is to be fully exhaustive with fold but that exploses quickly.


@PublishedApi
internal fun composeErrors(vararg other: Throwable?): Throwable? {
var a: Throwable? = null
other.forEach { b ->
when {
a == null -> a = b
b != null -> a?.addSuppressed(b)
else -> Unit
}
}
return a
}
nomisRev marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package arrow.core.computations

public object ResultEffect {
public fun <A> Result<A>.bind(): A = getOrThrow()
pablisco marked this conversation as resolved.
Show resolved Hide resolved
}

@Suppress("ClassName")
public object result {
public inline operator fun <A> invoke(c: ResultEffect.() -> A): Result<A> =
kotlin.runCatching { c(ResultEffect) }
}
nomisRev marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,40 @@ class IterableTest : UnitSpec() {
}
}

"traverseResult stack-safe" {
// also verifies result order and execution order (l to r)
val acc = mutableListOf<Int>()
val res = (0..20_000).traverseResult { a ->
acc.add(a)
Result.success(a)
}
res shouldBe Result.success(acc)
res shouldBe Result.success((0..20_000).toList())
}

"traverseResult short-circuit" {
checkAll(Arb.list(Arb.int())) { ints ->
val acc = mutableListOf<Int>()
val evens = ints.traverseResult {
if (it % 2 == 0) {
acc.add(it)
Result.success(it)
} else Result.failure(RuntimeException())
}
acc shouldBe ints.takeWhile { it % 2 == 0 }
evens.fold(
{ it shouldBe ints },
{ }
pablisco marked this conversation as resolved.
Show resolved Hide resolved
)
}
}

"sequenceResult should be consistent with traverseResult" {
checkAll(Arb.list(Arb.int())) { ints ->
ints.map { Result.success(it) }.sequenceResult() shouldBe ints.traverseResult { Result.success(it) }
}
}

"traverseOption is stack-safe" {
// also verifies result order and execution order (l to r)
val acc = mutableListOf<Int>()
Expand Down
Loading