Max*_*axG 5 io functional-programming either kotlin arrow-kt
我用箭头KT库,我想聘请Either并IO在同理解力。
说我有下一段代码:
IO.monad().binding {
val ans: Either<Error, Data> = someFunctionThatReturnsEitherWrappedInIO().bind()
}
Run Code Online (Sandbox Code Playgroud)
现在,我想在上使用绑定ans:
val data: Data = ans.bind() // My intent
Run Code Online (Sandbox Code Playgroud)
在第一段代码的范围内是否可以执行此操作?
当前,我正在尝试将Either绑定嵌套在IO绑定的范围内,但是我不确定这是一个好习惯:
IO.monad().binding {
val ans: Either<Error, Data> = someFunctionThatReturnsEitherWrappedInIO().bind()
val ansB: Either<Error, OtherData> = someOtherFunctionThatReturnsEitherWrappedInIO().bind()
val newData: Either<Any, NewData> = Either.monad<Any>().binding {
val data: Data = ans.bind()
val otherData: OtherData = ansB.bind()
NewData(data.a, otherData.lala)
}.fix()
}
Run Code Online (Sandbox Code Playgroud)
首先,我要指出,单子不撰写,这就是你需要的单子转换,你的情况EitherT是人,可以帮助你。
object Error
fun one() = IO { Right(1) }
fun two() = IO { Right("2") }
fun toInt(str: String) = IO { Try { str.toInt() }.toEither { Error } }
val result: IO<Either<Error, Int>> =
EitherT.monad<ForIO, Error>(IO.monad()).binding {
val oneInt = EitherT(one()).bind()
val twoString = EitherT(two()).bind()
val twoInt = EitherT(toInt(twoString)).bind()
oneInt + twoInt
}.value().fix()
println(result.unsafeRunSync()) // Just for demonstration, don't do this ever
Run Code Online (Sandbox Code Playgroud)
右(b = 3)
| 归档时间: |
|
| 查看次数: |
554 次 |
| 最近记录: |