我有三个简单的函数返回arrow-kt数据类型
fun validate(input): Validated<Error, Input> = ...
fun fetch(input): Option<Error, InputEntity> = ...
fun performAction(inputEntity): Either<Error, Output> = ...并希望这样的链接(可以使用任何可用的函数,而不是map)
validate(input)
.map{fetch(it)}
.map{performAction(it)} 我唯一能想出的解决方案是用Validated和Option代替Either,并使用flatMap来代替Either和chain。有什么更好的功能方法可以让它在不更新现有功能的情况下工作呢?
发布于 2020-07-20 08:33:58
@pablisco描述的内容是正确的,但您可以通过使用我们提供的一些语法扩展来将一种类型转换为另一种类型,从而使其更简单。请注意,这两个选项都是正确的,但是Monad Transformers可能有点复杂,功能太强大,而且一旦我们最终完全确定了我们的分隔延续样式,它们也很容易很快从Arrow中移除。但这不在范围之内。下面是如何通过使用我提到的扩展来解决这个问题:
import arrow.core.*
import arrow.core.extensions.fx
sealed class Error {
object Error1 : Error()
object Error2 : Error()
}
data class InputEntity(val input: String)
data class Output(val input: InputEntity)
fun validate(input: String): Validated<Error, InputEntity> = InputEntity(input).valid()
fun fetch(input: String): Option<InputEntity> = InputEntity(input).some()
fun performAction(inputModel: InputEntity): Either<Error, Output> = Output(inputModel).right()
fun main() {
val input = "Some input"
Either.fx<Error, Output> {
val validatedInput = !validate(input).toEither()
val fetched = !fetch(validatedInput.input).toEither { Error.Error1 /* map errors here */ }
!performAction(fetched)
}
}希望这是有用的
发布于 2020-07-20 06:38:55
你正在寻找的是所谓的Monad变压器。在Arrow中,您可能已经看到它们了,它们的结尾是一个T。比如OptionT或者EitherT。
这里有一些EitherT的好例子:
https://arrow-kt.io/docs/0.10/arrow/mtl/eithert/
这里是OptionT:
https://arrow-kt.io/docs/0.10/arrow/mtl/optiont/
这样做的想法是,为了选择最终值(假设两者之一),并使用FX块,您可以使用EitherT将其他类型转换为任意类型。
https://stackoverflow.com/questions/62988795
复制相似问题