Can we optimize this `futureOr` function: ``` s...
# arrow
t
Can we optimize this
futureOr
function:
Copy code
suspend fun fu(i: Int): Boolean = TODO()
    suspend fun futureOr(fs: List<Int>): Boolean =
        fs.parTraverse { fu(it) }.reduce { acc, b -> acc || b }
Now it needs to wait for all of suspend function completed. But we know that if there is one of the
fu(it)
return
false
we can return
false
and cancel the rest. Not sure how to do it nicely here.
s
Hey @thanh, You can do:
Copy code
suspend fun fu(i: Int): Boolean = TODO()

suspend fun futureOr(fs: List<Int>): Boolean =
  effect<Unit, Unit> {
    fs.parTraverse {
      if(fu(it)) Unit else shift(Unit)
    }    
  }.fold({ false }, { true })
👏 1
You can change the types in whatever way you want, but here
shift
makes the
parTraverse
short-circuit.
This also works with
either { }
from 1.x.x
t
It works great, thanks @simon.vergauwen
s
My pleasure @thanh 🙌
❤️ 1
j
shift
,
effect
- These are new to me. Where may I read more about them?
I found this.
s
Here is a small blog about when I first discovered this new abstraction: https://nomisrev.github.io/continuation-monad-in-kotlin/ The other blogs also use the
Effect
type, and might give you some more insights. It's new, but also not new 😄 It works 95% the same as
either { }
, and
either { }
is now build on top of
effect { }
.
TL;DR
suspend fun <E, A> either(f: suspend EffectScope<E>.() -> A): Either<E, A> = effect(f).toEither()
and
shift(e) <~~> e.left().bind()
If you feel something is missing please create an issue so we can improve the documentation over time, and absolutely feel free to create PRs with suggestions 😁 🙏
j
Thank you @simon.vergauwen!
🙌 1