gpt4 book ai didi

scala - 如何在 Scala 中使用具有类型类的路径相关类型

转载 作者:行者123 更新时间:2023-12-01 00:16:23 24 4
gpt4 key购买 nike

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

我有一些类型 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编译?我需要添加某种证据吗?

最佳答案

好像有点相似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 开始
  • 跳转自 aBar单例(通过模式匹配)
  • 使用 g从混凝土中获取 Bar单例到具体Baz[Array[Byte]]
  • 尝试返回此 Baz[Array[Byte]] ,似乎不再连接到 Baz[a.F] .

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

    关于scala - 如何在 Scala 中使用具有类型类的路径相关类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52304455/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com