6

假设我有以下功能:

def getRemoteThingy(id: Id): EitherT[Future, NonEmptyList[Error], Thingy]

给定 a ,我可以使用以下方法List[Id]轻松检索 a :List[Thingy]Traverse[List]

val thingies: EitherT[Future, NonEmptyList[Error], List[Thingy]] = 
  ids.traverseU(getRemoteThingy)

它将使用将基于的Applicative实例​​,所以我只会得到第一个,它不会附加所有这些。那是对的吗?EitherTflatMapNonEmptyList[Error]

现在,如果我真的想累积错误,我可以在EitherT和之间切换Validation。例如:

def thingies2: EitherT[Future, NonEmptyList[Error], List[Thingy]] = 
  EitherT(ids.traverseU(id => getRemoteThingy(id).validation).map(_.sequenceU.disjunction))

它有效,最后我得到了所有错误,但这很麻烦。我可以通过使用组合使其更简单:Applicative

type ValidationNelError[A] = Validation[NonEmptyList[Error], A]
type FutureValidationNelError[A] = Future[ValidationNelError[A]]
implicit val App: Applicative[FutureValidationNelError] =
  Applicative[Future].compose[ValidationNelError]

def thingies3: EitherT[Future, NonEmptyList[Error], List[Thingy]] = 
  EitherT(
    ids.traverse[FutureValidationNelError, Thingy](id => 
      getRemoteThingy(id).validation
    ).map(_.disjunction)
  )

比其他人更长,但所有管道都可以轻松地在代码库中共享。

你觉得我的解决方案怎么样?有没有更优雅的方法来解决这个问题?你通常是如何应对的?

非常感谢。

编辑:

我有一种使用自然转换来 pimp 的疯子解决方案Traversable。您显然需要类型别名才能使其工作,这就是我重新定义的原因getRemoteThingy

type FutureEitherNelError[A] = EitherT[Future, NonEmptyList[String], A]

def getRemoteThingy2(id: Id): FutureEitherNelError[Thingy] = getRemoteThingy(id)

implicit val EitherTToValidation = new NaturalTransformation[FutureEitherNelError, FutureValidationNelError] {
  def apply[A](eitherT: FutureEitherNelError[A]): FutureValidationNelError[A] = eitherT.validation
}

implicit val ValidationToEitherT = new NaturalTransformation[FutureValidationNelError, FutureEitherNelError] {
  def apply[A](validation: FutureValidationNelError[A]): FutureEitherNelError[A] = EitherT(validation.map(_.disjunction))
}

implicit class RichTraverse[F[_], A](fa: F[A]) {
  def traverseUsing[H[_]]: TraverseUsing[F, H, A] = TraverseUsing(fa)
}

case class TraverseUsing[F[_], H[_], A](fa: F[A]) {
  def apply[G[_], B](f: A => G[B])(implicit GtoH: G ~> H, HtoG: H ~> G, A: Applicative[H], T: Traverse[F]): G[F[B]] =
    HtoG(fa.traverse(a => GtoH(f(a))))
}

def thingies4: FutureEitherNelError[List[Thingy]] = 
  ids.traverseUsing[FutureValidationNelError](getRemoteThingy2)
4

0 回答 0