gpt4 book ai didi

scala - 尝试将 F 有界多态性建模为 Scala 中的类型成员

转载 作者:行者123 更新时间:2023-12-03 23:35:34 25 4
gpt4 key购买 nike

我想尝试编写一种类型,其方法可以是同类的并返回相同类型的值:

object SimpleTest {
trait Foo extends Product with Serializable {
type Self <: Foo
def bar: Self
}

case class X() extends Foo {
type Self = X
def bar = this
}

case class Y() extends Foo {
type Self = Y
def bar = this
}


trait TC[A]

implicit val tc: TC[Foo] = new TC[Foo] { }

def tester[A: TC](x: Seq[A]) = "foo"

// tester(Seq(X(), Y()))
}

不幸的是,注释掉的行调用 tester失败并出现以下错误(Scala 2.10):
Error: could not find implicit value for evidence parameter of type
SimpleTest.TC[SimpleTest.Foo{type Self >: SimpleTest.Y with SimpleTest.X <: SimpleTest.Foo}]
tester(Seq(X(), Y()))
^

基本上,我很困惑为什么 XY不统一到 Foo ,这对他们两个来说似乎是一个明确的 LUB。显然,类型成员使事情复杂化,但它的界限似乎得到了尊重。

在更高的层次上,我正在寻找一种轻量级的方法来获得等效的 F 有界多态性,而没有普遍类型参数的开销。这似乎很有效,但我需要添加强制 X 的注释。和 Y统一到 Foo .

最佳答案

我认为这是您正在寻找的示例:

sealed trait Event { self =>
type E >: self.type <: Event
def instance: E = self
}

case class UserJoined() extends Event {
type E = UserJoined
}

case class UserLeft() extends Event {
type E = UserLeft
}

如果你想阅读更多,这个片段来自 a recent post涵盖相关概念。

编辑:要完成答案,它将是:
scala> trait Foo extends Product with Serializable with Event{}
defined trait Foo

scala> case class X() extends Foo {
| type Self = X
| def bar = this
| }
defined class X

scala> case class Y() extends Foo {
| type Self = Y
| def bar = this
| }
defined class Y

scala> List(X(),Y())
res9: List[Foo] = List(X(), Y())

scala> def tester[A: TC](x: Seq[A]) = "foo"
tester: [A](x: Seq[A])(implicit evidence$1: TC[A])String

scala> tester(Seq(X(), Y()))
res10: String = foo

关于scala - 尝试将 F 有界多态性建模为 Scala 中的类型成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23481991/

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