Scala类型级编程 - 表示层次结构

Nig*_*olf 11 scala type-level-computation

我正在学习Scala中的类型级编程,我很好奇是否可以使用类型级编程来表示树或层次结构.

简单的情况是多层树

A_
  |
  B_
    |C
    |D
  |     
  E
Run Code Online (Sandbox Code Playgroud)

一个人如何代表这样的结构?

Tra*_*own 14

有许多方法可以表示Scala中的异构树,其中一个最简单的是这样的:

type MyTreeShape[A, B, C, D, E] = (A, (B, (C, D), E))
Run Code Online (Sandbox Code Playgroud)

这有一些限制(尽管你不能将元组作为叶子的值,因为我们在表示中使用了元组).对于这个答案的其余部分,我将使用一个涉及Shapeless的更复杂的表示HList:

import shapeless._

type MyTreeShape[A, B, C, D, E] =
  A ::
    (B ::
      (C :: HNil) ::
      (D :: HNil) ::
      HNil) ::
    (E :: HNil) ::
    HNil
Run Code Online (Sandbox Code Playgroud)

这里的树是一个树,HList其头部是值,其尾部是HList子树.

如果我们想对这些类型的树做一些有用的泛型,我们需要一些类型类.作为一个例子,我将FlattenTree在Shapeless的ops.hlist包中以类型类的模型快速编写深度优先.可以类似地实现尺寸,深度等的其他类型类.

这是类型类和方便的方法,使它易于使用:

trait FlattenTree[T <: HList] extends DepFn1[T] { type Out <: HList }

def flattenTree[T <: HList](t: T)(implicit f: FlattenTree[T]): f.Out = f(t)
Run Code Online (Sandbox Code Playgroud)

现在我们将放入伴随对象的实例:

object FlattenTree {
  type Aux[T <: HList, Out0 <: HList] = FlattenTree[T] { type Out = Out0 }

  implicit def flattenTree[H, T <: HList](implicit
    tf: FlattenForest[T]
  ): Aux[H :: T, H :: tf.Out] = new FlattenTree[H :: T] {
    type Out = H :: tf.Out

    def apply(t: H :: T): H :: tf.Out = t.head :: tf(t.tail)
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这需要一个帮助器类型,FlattenForest:

trait FlattenForest[F <: HList] extends DepFn1[F] { type Out <: HList }

object FlattenForest {
  type Aux[F <: HList, Out0 <: HList] = FlattenForest[F] { type Out = Out0 }

  implicit val hnilFlattenForest: Aux[HNil, HNil] = new FlattenForest[HNil] {
    type Out = HNil

    def apply(f: HNil): HNil = HNil
  }

  implicit def hconsFlattenForest[
    H <: HList,
    OutH <: HList,
    T <: HList,
    OutT <: HList
  ](implicit
    hf: FlattenTree.Aux[H, OutH],
    tf: Aux[T, OutT],
    pp: ops.hlist.Prepend[OutH, OutT]
  ): Aux[H :: T, pp.Out] = new FlattenForest[H :: T] {
    type Out = pp.Out

    def apply(f: H :: T): pp.Out = pp(hf(f.head), tf(f.tail))
  }
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以像这样使用它:

val myTree: MyTreeShape[String, Int, Char, Symbol, Double] =
  "foo" :: (10 :: HList('a') :: HList('z) :: HNil) :: HList(0.0) :: HNil

val flattened = flattenTree(myTree)
Run Code Online (Sandbox Code Playgroud)

让我们展示静态类型是否合适:

flattened: String :: Int :: Char :: Symbol :: Double :: HNil
Run Code Online (Sandbox Code Playgroud)

而这正是我们想要的.

你可以在没有Shapeless的情况下做到这一切,但它会涉及到令人难以置信的样板量.