gpt4 book ai didi

scala - 在 scala shapeless 中,是否可以将文字类型用作泛型类型参数?

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

假设我正在编写一个向量乘法程序。遵循本文中的要求:

https://etrain.github.io/2015/05/28/type-safe-linear-algebra-in-scala

只有当两个向量的维数相等时,乘法才能成功编译。为此,我定义了一个泛型类型 Axis使用无形状文字类型(维数)作为类型参数:

import shapeless.Witness

trait Axis extends Serializable

case object UnknownAxis extends Axis

trait KnownAxis[W <: Witness.Lt[Int]] extends Axis {

def n: Int

def ++(that: KnownAxis[W]): Unit = {}
}

object KnownAxis {

val w1 = Witness(1)
val w2 = Witness(2)

case class K1(n: Witness.`1`.T) extends KnownAxis[w1.type]
case class K2(n: Witness.`2`.T) extends KnownAxis[w2.type]

// K2(2) ++ K1(1) // doesn't compile

K2(2) ++ K2(2)
}

到目前为止一切顺利,但是当我尝试将其概括为所有 n 时,问题出现了:
  case class KN[W <: Witness.Lt[Int]](n: W#T) extends KnownAxis[W]

KN(1)

上面的代码触发编译错误:
Axis.scala:36: type mismatch;
found : Int(1)
required: this.T
[ERROR] KN(1)
[ERROR] ^
[ERROR] one error found

我的问题是:为什么Spark无法专注于更精致的类型 Witness.`1`.T ,而是使用类型 Int ?覆盖此行为需要什么,所以案例类 KN可以成功定义吗?

更新 1:后续已移至新问题:

When using the singleton type feature of Scala shapeless, how to force the compiler to use narrow/singleton type as an implicit parameter?

最佳答案

Scala 无法推断 W 也就不足为奇了给定 W#T ,因为一般来说可能有两个不同的 W s 具有相同的 W#T .不适用于见证类型,但编译器不会对其进行特殊处理。

我期望工作(并且不确定为什么不工作)是指定类型参数:

KN[Witness.`1`](1)
// error: type arguments [scala.this.Any] do not conform to method apply's type parameter bounds [W <: shapeless.this.Witness.Lt[scala.this.Int]]

或者更有可能
KN[w1.type](1)
// error: type mismatch;
// found : scala.this.Int(1)
// required: .this.T

什么工作:
case class KN[W <: Witness.Lt[Int]](w: W) extends KnownAxis[W] {
val n = w.value
}

KN(Witness(1))

它似乎符合您问题中的要求,但我不知道它是否适用于您的其余代码。

您可能还想考虑这种在 Scala 2.13 中不需要 Shapeless 的替代方案:
trait Axis extends Serializable

case object UnknownAxis extends Axis

trait KnownAxis[W <: Int with Singleton] extends Axis {

def n: W

def ++(that: KnownAxis[W]): Unit = {}
}

case class KN[W <: Int with Singleton](n: W) extends KnownAxis[W]

KN(1)

对于 2.12
import shapeless.syntax.singleton._

...
KN(1.narrow)

关于scala - 在 scala shapeless 中,是否可以将文字类型用作泛型类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60481612/

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