0

我有简单的三个函数返回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用. 有没有更好的功能方式让它在不更新现有功能的情况下工作?EitherflatMap

4

2 回答 2

2

@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-20T08:33:58.427 回答
1

您正在寻找的东西称为 Monad Transformer。在 Arrow 中,您可能已经看过它们,它们以 aT结尾。喜欢OptionTEitherT

这里有一些关于 EitherT 的好例子:

https://arrow-kt.io/docs/0.10/arrow/mtl/eithert/

在这里选项T:

https://arrow-kt.io/docs/0.10/arrow/mtl/optiont/

这个想法是选择你的最终值将是什么(假设是)并使用一个 FX 块,然后你可以使用它EitherT来将其他类型转换为一个 Either。

于 2020-07-20T06:38:55.037 回答