scala - 将其他列表转换为 HList 中的任一个

标签 scala shapeless

我想定义一个接受 HList 的函数,它的元素是这样的,对于每个元素 t,都有一个类型 T这样 t: Either[String, T]。我们将调用 validate 的函数应该具有以下行为:

  • 如果参数的所有元素都是Right,则返回用右投影映射参数的结果的Right
  • 否则,返回一个 Left[List[String]],其中列表包含参数中每个 Left 的左投影。

例子:

validate (Right (42) :: Right (3.14) :: Right (false) :: HNil)
>> Right (42 :: 3.14 :: false :: HNil)
validate (Right (42) :: Left ("qwerty") :: Left ("uiop") :: HNil)
>> Left (List ("qwerty", "uiop"))

示例用例:

case class Result (foo: Foo, bar: Bar, baz: Baz, qux: Qux)

def getFoo: Either[String, Foo] = ???
def getBar: Either[String, Bar] = ???
def getBaz: Either[String, Baz] = ???
def getQux: Either[String, Qux] = ???

def createResult: Either[String, Result] = {
    validate (getFoo :: getBar :: getBaz :: getQux :: HNil) match {
        case Right (foo :: bar :: baz :: qux :: HNil) => Right (Result (foo, bar, baz, qux))
        case Left (errors) => Left ("The following errors occurred:\n" + errors.mkString ("\n"))
    }
}

最佳答案

我假设在整个回答过程中我们都有这样的测试数据:

scala> import shapeless.{::, HNil}
import shapeless.{$colon$colon, HNil}

scala> type In = Either[String, Int] :: Either[String, String] :: HNil
defined type alias In

scala> val good: In = Right(123) :: Right("abc") :: HNil
good: In = Right(123) :: Right(abc) :: HNil

scala> val bad: In = Left("error 1") :: Left("error 2") :: HNil
bad: In = Left(error 1) :: Left(error 2) :: HNil

使用自定义类型类

有很多方法可以做到这一点。我可能会使用一个自定义类型类来强调实例的归纳构建方式:

import shapeless.HList

trait Sequence[L <: HList] {
  type E
  type Out <: HList
  def apply(l: L): Either[List[E], Out]
}

object Sequence {
  type Aux[L <: HList, E0, Out0 <: HList] = Sequence[L] { type E = E0; type Out = Out0 }

  implicit def hnilSequence[E0]: Aux[HNil, E0, HNil] = new Sequence[HNil] {
    type E = E0
    type Out = HNil
    def apply(l: HNil): Either[List[E], HNil] = Right(l)
  }

  implicit def hconsSequence[H, T <: HList, E0](implicit
    ts: Sequence[T] { type E = E0 }
  ): Aux[Either[E0, H] :: T, E0, H :: ts.Out] = new Sequence[Either[E0, H] :: T] {
    type E = E0
    type Out = H :: ts.Out
    def apply(l: Either[E0, H] :: T): Either[List[E0], H :: ts.Out] =
      (l.head, ts(l.tail)) match {
        case (Right(h), Right(t)) => Right(h :: t)
        case (Left(eh), Left(et)) => Left(eh :: et)
        case (Left(eh), _) => Left(List(eh))
        case (_, Left(et)) => Left(et)
      }
  }
}

然后你可以这样写validate:

def validate[L <: HList](l: L)(implicit s: Sequence[L]): Either[List[s.E], s.Out] = s(l)

然后像这样使用它:

scala> validate(good)
res0: scala.util.Either[List[String],Int :: String :: shapeless.HNil] = Right(123 :: abc :: HNil)

scala> validate(bad)
res1: scala.util.Either[List[String],Int :: String :: shapeless.HNil] = Left(List(error 1, error 2))

请注意,静态类型是正确的。

使用右折

你也可以用 Poly2 折叠起来更简洁一些。

import shapeless.Poly2

object combine extends Poly2 {
  implicit def eitherCase[H, T, E, OutT <: HList]:
    Case.Aux[Either[E, H], Either[List[E], OutT], Either[List[E], H :: OutT]] = at {
      case (Right(h), Right(t)) => Right(h :: t)
      case (Left(eh), Left(et)) => Left(eh :: et)
      case (Left(eh), _) => Left(List(eh))
      case (_, Left(et)) => Left(et) 
    }
}

然后:

scala> good.foldRight(Right(HNil): Either[List[String], HNil])(combine)
res2: scala.util.Either[List[String],Int :: String :: shapeless.HNil] = Right(123 :: abc :: HNil)

scala> bad.foldRight(Right(HNil): Either[List[String], HNil])(combine)
res3: scala.util.Either[List[String],Int :: String :: shapeless.HNil] = Left(List(error 1, error 2))

我想这可能是“正确”的答案,前提是您只想坚持使用 Shapeless。 Poly2 方法仅依赖于隐式解析的一些奇怪细节(例如,我们无法将 combine 定义为 val),我个人认为不太喜欢。

使用小猫的序列

最后你可以使用 Kittens库,支持排序和遍历 hlists:

scala> import cats.instances.all._, cats.sequence._
import cats.instances.all._
import cats.sequence._

scala> good.sequence
res4: scala.util.Either[String,Int :: String :: shapeless.HNil] = Right(123 :: abc :: HNil)

scala> bad.sequence
res5: scala.util.Either[String,Int :: String :: shapeless.HNil] = Left(error 1)

请注意,这不会累积错误。

如果你想要尽可能完整的 Typelevel 体验,我想你可以向 Kittens 添加一个 parSequence 操作,它会通过 Parallel 实例映射为 eithers 的 hlist 累积错误它们被Validated(参见my blog post here了解更多关于它是如何工作的细节)。不过,Kittens 目前不包含此内容。

更新:并行排序

如果您想要 parSequence,那么您自己编写它实际上并不是一场噩梦:

import shapeless.HList, shapeless.poly.~>, shapeless.ops.hlist.{Comapped, NatTRel}
import cats.Parallel, cats.instances.all._, cats.sequence.Sequencer

def parSequence[L <: HList, M[_], P[_], PL <: HList, Out](l: L)(implicit
  cmp: Comapped[L, M],
  par: Parallel.Aux[M, P],
  ntr: NatTRel[L, M, PL, P],
  seq: Sequencer.Aux[PL, P, Out]
): M[Out] = {
  val nt = new (M ~> P) {
    def apply[A](a: M[A]): P[A] = par.parallel(a)
  }

  par.sequential(seq(ntr.map(nt, l)))
}

然后:

scala> parSequence(good)
res0: Either[String,Int :: String :: shapeless.HNil] = Right(123 :: abc :: HNil)

scala> parSequence(bad)
res1: Either[String,Int :: String :: shapeless.HNil] = Left(error 1error 2)

请注意,这确实累积了错误,但通过连接字符串。在列表中累积错误的 Cats 惯用方法如下所示:

scala> import cats.syntax.all._
import cats.syntax.all._

scala> val good = 123.rightNel[String] :: "abc".rightNel[String] :: HNil
good: Either[cats.data.NonEmptyList[String],Int] :: Either[cats.data.NonEmptyList[String],String] :: shapeless.HNil = Right(123) :: Right(abc) :: HNil

scala> val bad = "error 1".leftNel[String] :: "error 2".leftNel[Int] :: HNil
bad: Either[cats.data.NonEmptyList[String],String] :: Either[cats.data.NonEmptyList[String],Int] :: shapeless.HNil = Left(NonEmptyList(error 1)) :: Left(NonEmptyList(error 2)) :: HNil

scala> parSequence(good)
res3: Either[cats.data.NonEmptyList[String],Int :: String :: shapeless.HNil] = Right(123 :: abc :: HNil)

scala> parSequence(bad)
res4: Either[cats.data.NonEmptyList[String],String :: Int :: shapeless.HNil] = Left(NonEmptyList(error 1, error 2))

可能值得打开一个 PR 来为 Kittens 添加类似的东西。

关于scala - 将其他列表转换为 HList 中的任一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59242860/

相关文章:

scala - Scala 创建不可变对象(immutable对象)的成本

java - 从 URL 构建 XML 对象时出现文件过早结束的情况

scala - 避免递归 MTL 类上的隐式扩展发散

scala - 获取密封特征的子类

scala - 关于此 Scala 模式匹配中未经检查的类型参数的警告?

java - 实例化参数类型的空对象

sql - Slick:传入列进行更新

scala - Slick 2.10-RC1,Scala 2.11.x,使用 case 类绕过 22 arity 限制(异构)

scala - 如何在 Scala 中将元素附加或前置到元组

scala - 使用Shapeless通过HList将Future的tuple转换为tuple的Future