我正在通过阅读“ Scala for the Im耐心”一书中的练习来学习Scala。一项练习要求:
编写一个循环,该循环交换整数数组的相邻元素。例如,Array(1、2、3、4、5)变为Array(2、1、4、3、5)
我用3种不同的方式来做到这一点,其中一种如下。我很好奇是否可以按照我的内联注释进行改进。
def swapWithGrouped(a: Array[Int]) = {
a.grouped(2).map {
// TODO: Can we use reverse here?
case Array(x, y) => Array(y, x)
// TODO: Can we use identity function here?
case Array(x) => Array(x)
}.flatten.toArray
}
您可以使用.flatMap
代替.map{..}.flatten
。
您也实际上并不需要匹配单个元素数组,因此您可以简单地使用一个变量(尽管我认为这确实取决于问题,有时显示模式中的对称性很好并且使意图更明确)。
所以 :
scala> def swapWithGrouped(a: Array[Int]) = {
a.grouped(2).flatMap {
case Array(x, y) => Array(y, x)
case single => single
}.toArray
}
swapWithGrouped: (a: Array[Int])Array[Int]
scala> swapWithGrouped(a) // a is Array(1,2,3,4,5)
res0: Array[Int] = Array(2, 1, 4, 3, 5)
这Array(x,y) => Array(y,x)
也很容易理解为错误,.reverse
使意图更加明确,并具有可以删除单元素情况的附加好处。
scala> def swapWithGrouped(a: Array[Int]) = a.grouped(2).flatMap(_.reverse).toArray
swapWithGrouped: (a: Array[Int])Array[Int]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句