1
我试图用我自己的方法来扩展TraversableLike,但是我失败了。通过使用自己的方法扩展TraversableLike来丰富我的库
首先,看看有什么我想实现:
class RichList[A](steps: List[A]) {
def step(f: (A, A) => A): List[A] = {
def loop(ret: List[A], steps: List[A]): List[A] = steps match {
case _ :: Nil => ret.reverse.tail
case _ => loop(f(steps.tail.head, steps.head) :: ret, steps.tail)
}
loop(List(steps.head), steps)
}
}
implicit def listToRichList[A](l: List[A]) = new RichList(l)
val f = (n: Int) => n * (2*n - 1)
val fs = (1 to 10) map f
fs.toList step (_ - _)
此代码工作正常,并计算出我的列表元素之间的差异。但我想有这样的代码,Seq
,Set
等,而不仅与List
。
我尝试这样做:
class RichT[A, CC[X] <: TraversableLike[X, CC[X]]](steps: CC[A]) {
def step(f: (A, A) => A): CC[A] = {
def loop(ret: CC[A], steps: CC[A]): CC[A] =
if (steps.size > 1) loop(ret ++ f(steps.tail.head, steps.head), steps.tail)
else ret.tail
loop(CC(steps.head), steps)
}
}
implicit def tToRichT[A, CC[X] <: TraversableLike[X, CC[X]]](t: CC[A]) = new RichT(t)
存在几个误区。隐式转换或++-method
都可以工作。另外,我不知道如何创建一个新类型的CC - 请参阅循环的调用。
我认为这个问题是一个重复的http://stackoverflow.com/questions/5410846 – 2011-04-11 19:53:24
可能的重复[如何将pimp-my-library模式应用到Scala集合?](http:// stackoverflow。 com/questions/5410846 /我该如何应用这个pimp-my-library-pattern-to-scala-collections) – 2011-04-12 15:01:24