For any given list or array, for instance
val list = (1 to 3).toList
val array = (1 to 3).toArray
and a given function that maps from and onto the collection type, for instance
def f(v: Int): Int = v + 10
how to apply f
to the ith element of list
or array
so that
list.myApply(f, ith = 2)
res: List(1,12,3)
and also
array.myApply(f, ith = 2)
res: Array(1,12,3)
Someone just asked about patch, so maybe this is a duplicate:
Generalizing a smidgen:
This was my first go, as Chris prompts:
So as Chris was saying:
And good night, Gracie.
It is very complex to add additional methods to the existing collections with implicits. If using an external method OK, this is a solution. Almost there but not quite. Example in a Scala IDE worksheet
In the case of an array, it returns an ArrayBuffer instead of Array. For all other Seq types works properly. I have tried many other combinations but nothing fixes this issue.
This zipWithIndex returns an ArrayBuffer but if
val a: Array[Int]
is used,zipWithIndex
returns an Array.The vagaries of retro-fitting Java arrays into collections I guess.
tl;dr
Discussion
A naive approximation:
Example usage:
Attempted actual solution:
Unfortunately, the implicit doesn't work. I'm not sure why.
Edit: Fixed it!
Example:
But I just realized you also wanted it to work for
Array
, which isn'tSeqLike
, so let me think some more...Ah,
Predef
has an implicit conversion fromArray
toArrayOps
, which is a subtype ofSeqLike
, so we just need to use a view bound.And finally we have the right behavior:
Edit again - samthebest informs me that view bounds are deprecated, so using this guide we can replace it with a very ugly-looking context bound.