F型有界多型在返回类问题上的优势

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

Returning the current type个问题通常在StackOverflow上问。 Here就是这样一个例子。通常的答案似乎是F-bounded polymorphismtypeclass模式解决方案。奥德斯基在Is F-bound polymorphism useful?中建议

F边界确实确实增加了很大的复杂性。我希望能够摆脱它们,并用更高级的子类型替换它们]

虽然tpolecat(链接为post的作者建议]

更好的策略是使用类型类,它可以解决问题干净利落,几乎没有余地。其实值得考虑完全放弃这些亚型多态性情况。

确定以下disadvantage的地方

F界多态性将类型参数化为其自身的子类型,这是一个比用户通常想要的要弱的约束,是说“我的类型”的一种方式,您无法通过子类型化。但是类型类可以直接表达这个想法,所以那就是我要教的初学者

我的问题是,根据上述建议,有人可以证明F界多态性是有利的情况,还是我们应该将类型分类解决方案作为解决return-current-type

问题的规范答案?

F绑定的类型参数多态性

trait Semigroup[A <: Semigroup[A]] {
  def combine(that: A): A
}

case class Foo(v: Int) extends Semigroup[Foo] {
  def combine(that: Foo): Foo = Foo(this.v + that.v)
}

case class Bar(v: String) extends Semigroup[Bar] {
  def combine(that: Bar): Bar = Bar(this.v concat that.v)
}

def reduce[A <: Semigroup[A]](as: List[A]): A = as.reduce(_ combine _)

reduce(List(Foo(1), Foo(41)))        // res0: Foo = Foo(42)
reduce(List(Bar("Sca"), Bar("la")))  // res1: Bar = Bar(Scala)

按类型成员的F界多态性

trait Semigroup {
  type A <: Semigroup
  def combine(that: A): A
}

case class Foo(v: Int) extends Semigroup {
  type A = Foo
  def combine(that: Foo): Foo = Foo(this.v + that.v)
}

case class Bar(v: String) extends Semigroup {
  type A = Bar
  def combine(that: Bar): Bar = Bar(this.v concat that.v)
}

def reduce[B <: Semigroup { type A = B }](as: List[B]) =
  as.reduce(_ combine _)

reduce(List(Foo(1), Foo(41)))        // res0: Foo = Foo(42)
reduce(List(Bar("Sca"), Bar("la")))  // res1: Bar = Bar(Scala)

Typeclass

trait Semigroup[A] {
  def combine(x: A, y: A): A
}

case class Foo(v: Int)
case class Bar(v: String)

implicit object FooSemigroup extends Semigroup[Foo] {
  def combine(x: Foo, y: Foo): Foo = Foo(x.v + y.v)
}

implicit object BarSemigroup extends Semigroup[Bar] {
  def combine(x: Bar, y: Bar): Bar = Bar(x.v concat y.v)
}

def reduce[A](as: List[A])(implicit ev: Semigroup[A]): A = as.reduce(ev.combine)

reduce(List(Foo(1), Foo(41)))        // res0: Foo = Foo(42)
reduce(List(Bar("Sca"), Bar("la")))  // res1: Bar = Bar(Scala)

返回当前类型的问题通常在StackOverflow上询问。这是一个这样的例子。常见的答案似乎是F界多态性或类型类模式解决方案。奥德斯基...

scala typeclass f-bounded-polymorphism return-current-type
1个回答
1
投票

[我建议类型类确实是上等模式,并且对于“返回当前类型”问题的任何F绑定多态解决方案,如果不是更好的并行类型,都具有同样好的效果。

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