Youssef Shoaib [MOD]
02/21/2025, 5:56 PMfold
, in its full generality, can be implemented thru merge
(and an even more-restricted version attempt
)
public inline fun <Error> attempt(block: Raise<Error>.() -> Nothing): Error = merge(block)
public inline fun <Error, A, B> fold(
block: Raise<Error>.() -> A,
catch: (throwable: Throwable) -> B,
recover: (error: Error) -> B,
transform: (value: A) -> B,
): B {
val success = run success@{
val error = catch({ attempt { return@success block(this) } }) { return catch(it) }
return recover(error)
}
return transform(success)
}
This works because of the magic of inline
!