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]
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.
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( _-_ )
When you use seq.view
in your code, you are creating SeqView[Int, Seq[Int]]
objects that cannot be zipped, as it can't support TraversableView.Builder.result
. But you can use something like this:
def diffInt(seq: Seq[Int]) = {
val v1 = seq.view(0,seq.size-1)
val v2 = seq.view(1,seq.size)
(v2.toList,v1.toList).zipped.map {
case (x1: Int, y1: Int) => x1-y1
case _ => 0
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With