2016-07-31 1 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

시도는 다음과 같이 대신)합니다 (odd_concat 내부에 그 코드를 삽입 .2 % 2! = 0) .map (t => t._1)' – Brian

+0

또는'arr.sliding (2,2) .flatMap (_. tail) .toList' – jwvh

답변

2

변경할 수없는 목록을 사용하고 있습니다. 변경 불가능한 것은 개체를 변경할 수 없음을 의미합니다.

귀하의 코드 : 값이 추가로

list_odd:+arr(arr_index) 

그것은 편곡 (arr_index)의 값으로 list_odd을 변경하지 않습니다 오히려 목록의 새로운 인스턴스를 제공합니다.

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) 
} 
관련 문제