简体   繁体   English

Scala:类型类的层次结构和隐式解析

[英]Scala: hierarchy of typeclasses and implicit resolution

Suppose I'm trying to represent, say, the domain of boolean logic (ignoring reduction for now). 假设我要表示布尔逻辑的域(暂时忽略约简)。 So I'll have in my store instances of Bools, or Ands and Ors or Nots etc. However, whilst I'll have concrete representations for these things, in many cases all I'll care about is that something can, say, be viewed as a Bool, or as a combination of two Bools (this doesn't quite make sense here, but the bigger example is some kind of heterogenous data store where I might request, say, all things that might have a colour). 因此,我将在商店中使用Bools,Ands和Ors or Nots等实例。但是,尽管我将具体表示这些东西,但在许多情况下,我只关心可以被视为Bool或两个Bool的组合(在这里并不太有意义,但是更大的示例是某种异构数据存储,我可能会在其中请求所有可能有颜色的东西)。 There are multiple potential hierarchies, so subclassing doesn't really cut it, and since I want to avoid explicit conversion, typeclasses seem to be the way to go. 有多个潜在的层次结构,因此子类化并没有真正消除它,并且由于我想避免显式转换,所以类型类似乎是解决之道。 So I have something like this: 所以我有这样的事情:

trait Delegated[-B, +A] {
  def bind(b : B) : A
}

trait Thing[A <: Thing[A]] {
  type Class[B] = Delegated[B,A]
}


trait BoolLike extends Thing[BoolLike] {
  def value : Boolean
}
class Bool(val value : Boolean) extends BoolLike

Now, however, to avoid repeating myself, I would like to specify that, for any Thing , a subclass will satisfy Thing#Class . 但是,现在为了避免重复我自己,我想对所有Thing指定一个子类将满足Thing#Class So my attempt at this was the following: 因此,我的尝试如下:

implicit def SubclassIsClass[A <: Thing[A], B <: A] : A#Class[B] = new A#Class[B] { 
  def bind(b : B) = b
}

However, if I do 但是,如果我这样做

implicitly[BoolLike#Class[Bool]]

I get no evidence, yet I can quite happily call SubclassIsClass[BoolLike, Bool] and get an appropriate Delegate. 我没有证据,但是我可以很高兴地调用SubclassIsClass[BoolLike, Bool]并获得适当的委托。 Should this be implicitly inferrable? 这应该隐含地推论吗?

Solved it - if I change 解决了-如果我改变

trait Delegated[-B, +A]

to

trait Delegated[B,A]

then this works. 然后这个工作。 Given that the annotations were left over from a different way of doing things, this seems like a fine solution. 鉴于注释是通过其他处理方式留下的,这似乎是一个很好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM