In the book that I'm studying there is an exercise:
Write a loop that swaps adjacent elements of an array of integer. For example
Array(1,2,3,4,5)
becomesArray(2,1,4,3,5)
. My solution is:
var v = Array(0,1,2,3,4,5,6,7,8,9)
for (i <- 0 until v.length by 2) {
var temp = 0
temp = v(i+1); v(i+1) = v(i); v(i) = temp
}
This algorithm works fine but isn't written fully exploiting the potential of Scala, it is written as if I wrote in C++. In fact, the following exercise asks:
Repeat the preceding assignment, but produce a new array with the swapped values. Use for/yield.
Now I tried with:
val a = ArrayBuffer(1,2,3,4,5)
var res = for (i <- 0 until a.length by 2) yield a(i)
for (i <- 1 until a.length by 2) res(i-1)=a(i) <---------eclipse give me an error
The error is: "value update is not a member of scala.collection.immutable.IndexedSeq[Int]"
How can I solve this task? I understand that the syntax "for / yield" is very powerful, but I don't know how to use it.