Cats:使用相同的应用程序映射元组

问题描述 投票:4回答:1

比方说我有:

val x1: Either[String, Int] = Right(1)
val x2: Either[String, Float] = Left("Nope")
val x3: Either[String, Double] = Left("Not Today")

我想把这些结合起来得到一个Either[NonEmptyList[String], (Int, Float, Double)]。为此,我目前正在执行以下操作:

import cats.syntax.all._
(
  x1.toValidatedNel,
  x2.toValidatedNel,
  x3.toValidatedNel
).tupled
 .toEither

这项工作做得多但有点单调乏味。有没有办法通过只调用一次toValidatedNel来做到这一点?就像是:

(x1, x2, x3)
  .fooMap(_.toValidatedNel)
  .tupled
  .toEither

这样的fooMap是否存在于猫的某个地方?或者我们需要HLists吗?

scala tuples scala-cats applicative either
1个回答
3
投票

使用Shapeless,就是这样

import shapeless.syntax.std.tuple._
object toValidatedNel extends Poly1 {
  implicit def cse[A, B, AA >: A]: Case.Aux[Either[A, B], ValidatedNel[AA, B]] = at(_.toValidatedNel[AA])
}

(x1, x2, x3)
  .map(toValidatedNel)
  .tupled
  .toEither
© www.soinside.com 2019 - 2024. All rights reserved.