scala - Enrich-my-library by extending TraversableLike with own methods -


i tried extend traversablelike own methods, failed.

first, see wanna achieve:

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 10) map f fs.tolist step (_ - _) 

this code works fine , calculates me differences between list elements. wanna have such code works seq, set etc. , not list.

i tried this:

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) 

there several errors. either implicit conversion nor ++-method work. also, don't know how create new type cc - see call of loop.

based on rex' comment have written following code:

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 = cbfc()      if (iter.hasnext) {       var olda = iter.next       += olda       while (iter.hasnext) {         val = iter.next         += f(a, olda)         olda =       }     }     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 10) map f fs step (_ - _) 

this works expected.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -