Scala for / yield语法 [英] Scala for/yield syntax
问题描述
在我正在学习的书中有一个练习:
编写一个循环来交换整数数组的相邻元素。例如
Array(1,2,3,4,5)
变成Array(2,1,4,3,5)
。我的解决方案是:
var v = Array(0,1,2,3,4 (i < - 0,直到v.length为2)(
var temp = 0
temp = v(i + 1) ; v(i + 1)= v(i); v(i)= temp
}
这个算法可以正常工作,利用Scala的潜力,就像我用C ++写的一样。实际上,下面的练习要求:
重复前面的赋值,但是生成一个新的数组。使用 for / yield 。
现在我尝试了:
val a = ArrayBuffer(1,2,3,4,5)
var res = for(i < - 0,直到a.length减去2)得到一个(i)$ b $ (i <-1直到a.length减去2)res(i-1)= a(i)<--------- eclipse给我一个错误
错误是:值更新不是scala.collection.immutable.IndexedSeq [Int]的成员
我该如何解决这个问题?我知道for / yield的语法是非常强大的,但是我不知道如何使用它。 解决方案
有一个滑动
函数可以完全满足您的需求:
( for {
i< - Array(1,2,3,4,5).sliding(2,2)
j< - i.reverse
} yield j).toArray
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.
There is a sliding
function that does exactly what you need:
(for {
i <- Array(1,2,3,4,5).sliding(2,2)
j <- i.reverse
} yield j).toArray
这篇关于Scala for / yield语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!