I tried to figure out how to write a functional swap function that works on any Traversable[_] , given the collection and swap indices. I came up with the following:
def swap[A, CC <% Traversable[A]](xs: CC, i: Int, j: Int): Traversable[A] = { xs.slice(0, i) ++ xs.slice(j, j+1) ++ xs.slice(i+1, j) ++ xs.slice(i, i+1) ++ xs.slice(j+1, xs.size) } swap(List(1,2,3,4,5), 0, 4) // => List(5,2,3,4,1)
I would like to know how to do this in an implicit Traversable extension, letting me call it List(1,2,3,4,5).swap(0, 4) . The closest I could get is this:
import language.implicitConversions class RichTraversable[A, B <% Traversable[A]](xs: B) { def swap(i: Int, j: Int): Traversable[A] = { xs.slice(0, i) ++ xs.slice(j, j+1) ++ xs.slice(i+1, j) ++ xs.slice(i, i+1) ++ xs.slice(j+1, xs.size) } } implicit def richTraversable[A, B <% Traversable[A]](ys: B)(implicit b: Traversable[A]) = new RichTraversable[A, B](ys)
Unfortunately, this is not entirely true. Calling List(1,2,3,4,5).swap(0, 4) results in the following error:
error: implicit view from the list [Int] => Traversable [A] is not available
I feel that I am missing something, or that complicates the problem too much. Does anyone know how this should be structured?
Note. It is purely academic and is not used in any way in the production environment. I am trying to get a better system descriptor and restrictions like Scala.