2016-07-31 4 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(トン=>トン.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) 
}