2016-07-31 24 views
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) 
} 
+1

在我看來,多一點你的方法的功能和更清晰的:'arr.zipWithIndex.filter(T => T ._2%2!= 0).map(t => t._1)' – Brian

+0

或者,'arr.sliding(2,2).flatMap(_。tail).toList' – jwvh

回答

2

您正在使用不可變列表,不可變意味着對象無法更改。

您的代碼:

list_odd:+arr(arr_index) 

它不改變與ARR(arr_index)的值list_odd寧願放棄名單的新實例值增加。

嘗試插入代碼的odd_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) 
}