Scala 返回值位于奇数位置的列表
为什么下面的代码返回一个空列表,而不是一个值位于奇数位置的列表Scala 返回值位于奇数位置的列表,scala,Scala,为什么下面的代码返回一个空列表,而不是一个值位于奇数位置的列表 def f(arr:List[Int]) : List[Int] = { def odd_concat(list_odd:List[Int], arr_index:Int) : List[Int] = { if(arr_index == arr.size) { list_odd } else if(arr_index % 2 == 0) {
def f(arr:List[Int]) : List[Int] = {
def odd_concat(list_odd:List[Int], arr_index:Int) : List[Int] = {
if(arr_index == arr.size) {
list_odd
}
else if(arr_index % 2 == 0) {
odd_concat(list_odd, arr_index + 1)
}
else {
//println(arr(arr_index))
list_odd:+arr(arr_index)
odd_concat(list_odd, arr_index + 1)
}
}
odd_concat(List(), 0)
}
您使用的是不可变列表,不可变意味着对象无法更改 您的代码:
list_odd:+arr(arr_index)
它不会使用arr(arr_index)的值更改list_odd,而是使用添加的值提供list的新实例
请尝试将该代码插入奇数_concat()中,如下所示:
def f(arr:List[Int]) : List[Int] = {
def odd_concat(list_odd:List[Int], arr_index:Int) : List[Int] = {
if(arr_index == arr.size) {
list_odd
}
else if(arr_index % 2 == 0) {
odd_concat(list_odd, arr_index + 1)
}
else {
//println(arr(arr_index))
odd_concat(list_odd:+arr(arr_index), arr_index + 1)
}
}
odd_concat(List(), 0)
}
您使用的是不可变列表,不可变意味着对象无法更改 您的代码:
list_odd:+arr(arr_index)
它不会使用arr(arr_index)的值更改list_odd,而是使用添加的值提供list的新实例
请尝试将该代码插入奇数_concat()中,如下所示:
def f(arr:List[Int]) : List[Int] = {
def odd_concat(list_odd:List[Int], arr_index:Int) : List[Int] = {
if(arr_index == arr.size) {
list_odd
}
else if(arr_index % 2 == 0) {
odd_concat(list_odd, arr_index + 1)
}
else {
//println(arr(arr_index))
odd_concat(list_odd:+arr(arr_index), arr_index + 1)
}
}
odd_concat(List(), 0)
}
比你的方法更实用,在我看来更清晰:
arr.zipWithIndex.filter(t=>t.\u2%2!=0).map(t=>t.\u1)
Or,arr.slide(2,2).flatMap(\u2.tail).toList
比你的方法更实用,在我看来更清晰:arr.zipWithIndex.filter(t=>t.\u2%2!=0).map(t=>t.\u1)
Or,arr.slideing(2,2).flatMap(u.tail).toList