Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failure parsing views

Tags:

scala

seq

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( _-_ )

like image 974
Juh_ Avatar asked Mar 02 '16 13:03

Juh_


1 Answers

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
  }
}
like image 155
Carlos Vilchez Avatar answered Sep 24 '22 07:09

Carlos Vilchez