I define the following diff function on Seq[Int]
which uses view
to avoid copying data:
object viewDiff {
def main(args: Array[String]){
val values = 1 to 10
println("diff="+diffInt(values).toList)
}
def diffInt(seq: Seq[Int]): Seq[Int] = {
val v1 = seq.view(0,seq.size-1)
val v2 = seq.view(1,seq.size)
(v2,v1).zipped.map(_-_)
}
}
This code fails with an UnsupportedOperationException
. If I uses slice
instead of view
it works.
Can anyone explain this?
[tested with scala 2.10.5 and 2.11.6]
Edit
I selected Carlos's answer because it was the (first) correct explanation of the problem. However, som-snytt's answer is more detailed, and provides a simple solution using view on the zipped object.
I also posted a very simple solution that works for this specific case.
Note
In the code above, I also made a mistake on the algorithm to compute a seq derivative. The last line should be: seq.head +: (v2,v1).zipped.map( _-_ )