[英]Scala generics: type mismatch with folding
scala新手。 試圖理解為什么scala編譯器對以下內容不滿意:
sealed trait LinkedList[A] {
def fold[B](end: B)(func: (A, B) => B): B =
this match {
case End() => end
case Pair(hd, tl) => func(hd, tl.fold(end)(func))
}
def sum: Int =
fold[Int](0){(hd, tl) => hd + tl}
}
final case class Pair[A](head: A, tail: LinkedList[A]) extends LinkedList[A]
final case class End[A]() extends LinkedList[A]
object Foo extends App {
val example = Pair(1, Pair(2, Pair(3, End())))
println(example.sum)
}
得到此錯誤:
Error:(10, 35) type mismatch;
found : Int
required: String
fold[Int](0){(hd, tl) => hd + tl}
如何在這里推斷出String?
請幫忙。
對於一般A
,通常的“添加”沒有定義。 因此,它隱式地將A
轉換為String
,並使用連接String
的+
。 一個快速而骯臟的解決方法是:
def sum(implicit i: A =:= Int): Int = fold[Int](0){(hd, tl) => i(hd) + tl}
只有當A
是Int
才會使sum
可用。 一種更為系統化的方法是使用Numeric
類型類,就像標准庫中的方法一樣(展開“用例”和“完全簽名”)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.