Defining implicit view-bounds on Scala traits

后端 未结 3 1063
长情又很酷
长情又很酷 2021-02-13 10:28

I\'m doing an exercise to implement a functional binary-search-tree in Scala, following a similar pattern that I\'ve seen used in Haskell. I have a structure that looks somethin

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 11:23

    You could provide the "evidence" that A is Ordered by requiring an abstract member of type Ordered[A] on the trait:

    trait TreeNode[A] {
      implicit val evidence: Ordered[A]
    }
    

    You would then be forced to provide this in any concrete subtypes, this proving that A is Ordered:

    case class Leaf[A](value: A)(implicit ev: Ordered[A]) extends TreeNode[A] {
      val evidence = ev
    }
    

    You might instead want to constrain A to a type which has an implicit Ordering[A] - this is not an inheritance relationship; it is more like a haskell typeclass. But the implementation in terms of the above technique would be the same.

提交回复
热议问题