7
正如我已知使用無形不同類型的列表,不成形提供HList
(異構列表)類型,其可以包括多個類型。摺疊Scala中
是否可以摺疊HList
?例如,
// ref - Composable application architecture with reasonably priced monad
// code - https://github.com/stew/reasonably-priced/blob/master/src/main/scala/reasonable/App.scala
import scalaz.{Coproduct, Free, Id, NaturalTransformation}
def or[F[_], G[_], H[_]](f: F ~> H, g: G ~> H): ({type cp[α] = Coproduct[F,G,α]})#cp ~> H =
new NaturalTransformation[({type cp[α] = Coproduct[F,G,α]})#cp,H] {
def apply[A](fa: Coproduct[F,G,A]): H[A] = fa.run match {
case -\/(ff) ⇒ f(ff)
case \/-(gg) ⇒ g(gg)
}
}
type Language0[A] = Coproduct[InteractOp, AuthOp, A]
type Language[A] = Coproduct[LogOp, Language0, A]
val interpreter0: Language0 ~> Id = or(InteractInterpreter, AuthInterpreter)
val interpreter: Language ~> Id = or(LogInterpreter, interpreter0)
// What if we have `combine` function which folds HList
val interpreters: Language ~> Id = combine(InteractInterpreter :: AuthInterpreter :: LoginInterpreter :: HNil)
即使可以簡化Langauge
的生成嗎?
type Language0[A] = Coproduct[InteractOp, AuthOp, A]
type Language[A] = Coproduct[LogOp, Language0, A]
// What if we can create `Language` in one line
type Language[A] = GenCoproduct[InteractOp, AuthOp, LogOp, A]
您可以使用多態函數摺疊'HList'。請參閱[無形指南](https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#heterogenous-lists)。 –