Scala 如何筛选按非降序排列的元素列表
如何筛选其他列表的列表,例如Scala 如何筛选按非降序排列的元素列表,scala,Scala,如何筛选其他列表的列表,例如 val l = List(List(1,2,3), List(1,2,4), List(9,8,7)) 要返回一个不按降序排列的元素列表,列表中的元素和是奇数。因此它应该返回列表(1,2,4)(总和为7,元素不是按降序排列) 我在考虑类似于l.filter(l.head
val l = List(List(1,2,3), List(1,2,4), List(9,8,7))
要返回一个不按降序排列的元素列表,列表中的元素和是奇数。因此它应该返回列表(1,2,4)
(总和为7,元素不是按降序排列)
我在考虑类似于
l.filter(<\uu).filter(+\u%2!=0)
的东西,但我真的不知道如何做到这一点。您可以检查排序列表是否与列表本身相同:
val filtered = l.filter(x => x.sorted == x && x.sum % 2 != 0)
@Luis指出的尾部递归方法:
def isAscendingAndOddSum(xss: List[List[Int]]): List[List[Int]] = {
@scala.annotation.tailrec
def isAscendingAndOddSumR(xss: List[List[Int]], acc: List[List[Int]]): List[List[Int]] = xss match {
case Nil => acc
case h::t if(h.sorted == h && h.sum % 2 != 0) => isAscendingAndOddSumR(t, h :: acc)
case h::t => isAscendingAndOddSumR(t, acc)
}
isAscendingAndOddSumR(xss, List())
}
scala> isAscendingAndOddSum(List(List(1,2,3), List(1,2,4), List(9,8,7)))
val res11: List[List[Int]] = List(List(1, 2, 4))
我个人会为此编写一个尾部递归算法或使用
foldLeft
。效率更高一点:def isSorted(list:list[Int])=list.slideing(2)。forall{l=>l.head