Hi, I'm playing a bit with the computation blocks;...
# arrow
h
Hi, I'm playing a bit with the computation blocks; I'm trying to understand what is the best way to compose blocks for nested monads. As an example:
Copy code
val str1 = "hello".toOption().right()
    val str2 = "world".toOption().right()

    val output: Either<Any, Option<String>> = either {
        option {
            val value1 = str1.bind().bind()
            val value2 = str2.bind().bind()
            value1 + value2
        }
    }
I'm wondering if there is any "generic" way compose in order to obtain (for this example) an
eitherOption { }
block where I can call
.bind()
just one time. I know that Option and Either nested like this are not so useful, this is just for having a simple example 😃
s
With Multiple Receivers we can just do the following:
Copy code
context(EitherEffect<E>, OptionEffect)
suspend fun <E, A> Either<E, Option<A>.bind(): A = bind().bind()
Performance wise there is no penalty since it just uses
inline fold
underneath the hood
It’s currently not possible to defined that in Kotlin, unless you do some manual wiring
The only way to do this currently is to define:
Copy code
interface EitherOptionEffect : EitherEffect<E> OptionEffect {
  suspend fun <E, A> Either<E, Option<A>.bind(): A
}
Which you can make concrete by doing something likee
Copy code
suspend <E, A>. optionEither(f: suspend EitherOptionEffect<E>.() -> A): Either<E, Option<A>> {
  either<E, Option<A>> {
    option<A> {
      f(object : EitherOptionEffect<E>,
           EitherEffect<E> by this@either,
           OptionEffect by this@option { })
    }
  }
}
h
Ok, Thank you @simon.vergauwen, I got it