2011-04-11 61 views
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 - 请参阅循环的调用。

+0

我认为这个问题是一个重复的http://stackoverflow.com/questions/5410846 – 2011-04-11 19:53:24

+0

可能的重复[如何将pimp-my-library模式应用到Scala集合?](http:// stackoverflow。 com/questions/5410846 /我该如何应用这个pimp-my-library-pattern-to-scala-collections) – 2011-04-12 15:01:24

回答

2

基于雷克斯”的评论我已经写了下面的代码:

class RichIter[A, C[A] <: Iterable[A]](ca: C[A]) { 
    import scala.collection.generic.CanBuildFrom 
    def step(f: (A, A) => A)(implicit cbfc: CanBuildFrom[C[A], A, C[A]]): C[A] = { 
    val iter = ca.iterator 
    val as = cbfc() 

    if (iter.hasNext) { 
     var olda = iter.next 
     as += olda 
     while (iter.hasNext) { 
     val a = iter.next 
     as += f(a, olda) 
     olda = a 
     } 
    } 
    as.result 
    } 
} 
implicit def iterToRichIter[A, C[A] <: Iterable[A]](ca: C[A]) = new RichIter[A, C](ca) 

val f = (n: Int) => n * (2*n - 1) 
val fs = (1 to 10) map f 
fs step (_ - _) 

可正常工作。

+0

非常有用的答案。我可以剪切并粘贴并添加适合的方法,并在稍后了解更详细的细节。 – 2012-10-11 17:07:48