如何在Scala中使用具有类型类的路径依赖类型

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

我在路径依赖类型方面遇到了一些问题。

我有一些类型Foo与抽象类型成员F。像Bar这样的实例将提供具体类型。

然后有一个类型类Baz。我有每种具体类型的Foo#F类型类的实例(但不适用于Foo本身)。

这是一个例子:

sealed trait Foo {
  type F
}

object Bar extends Foo {
  type F = Array[Byte]
}

trait Baz[B] {
  def b(b: B): String
}

object Baz {
  implicit val bazByteArray: Baz[Array[Byte]] = (b: Array[Byte]) => new String(b)
}

我无法编译:

def f(a: Foo): Baz[a.F] = {
  val baz = a match {
    case bar@Bar => g(bar)
  }
  baz
} // Expression of type Baz[(a.type with Bar.type)#F] doesn't conform to Baz[a.F]

val x2: Foo = Bar
val y2: Baz[x2.F] = f(x2) // Expression of type Baz[Foo#F] doesn't conform to expected type Baz[x2.F]

这确实编译:

def g(a: Foo)(implicit baz: Baz[a.F]): Baz[a.F] = {
  baz
}

val x1: Bar.type = Bar
val y1: Baz[x1.F] = f(x1)

为什么g编译而不是f?这些类型不一样吗?

我怎样才能让f编译?我需要添加某种证据吗?

scala types typeclass path-dependent-type
1个回答
4
投票

似乎有点类似to this question。这是一种使其编译的方法:

sealed trait Foo {
  type F
  def asSingleton: FooSingleton[F]
}

trait FooSingleton[X] extends Foo {
  type F = X
  def asSingleton: FooSingleton[X] = this
}

object Bar extends FooSingleton[Array[Byte]]

trait Baz[B] {
  def b(b: B): String
}

object Baz {
  implicit val bazByteArray: Baz[Array[Byte]] = 
    (b: Array[Byte]) => new String(b)
}

def g(a: Foo)(implicit baz: Baz[a.F]): Baz[a.F] = {
  baz
}

val x1: Bar.type = Bar
val y1: Baz[x1.F] = f(x1)

def f[T](a: Foo { type F = T } ): Baz[T] = {
  (a.asSingleton: FooSingleton[T]) match {
    case bar @ Bar => g(bar)
  }
}

val x2: Foo = Bar
val y2: Baz[x2.F] = f(x2)

你的g编译,因为baz类型的路径依赖参数Baz[a.F]来自外部,编译器插入一个具体的隐式实例,并且实际值a不在g内的任何地方使用。

你的f不能编译,因为B[a.F]只出现在返回类型中,并且在实际参数a传递给f之前它不能更具体。

从某种意义上说,f打破了参数a和返回值之间的路径,因为它会产生以下“不连续跳跃”:

  • a: Foo开始
  • a跳到Bar单身(通过模式匹配)
  • 使用g从混凝土Bar单身人士到混凝土Baz[Array[Byte]]
  • 试图返回这个Baz[Array[Byte]],它似乎不再与Baz[a.F]相关联。

这条路径可以通过证明不连续的“跳跃”确实只是一直保持在同一点的身份路径来修复,因此它实际上不会移动到任何地方,因此a.F和推断类型是相同的,即T

© www.soinside.com 2019 - 2024. All rights reserved.