scala

[spark] zipWithIndex, for-yield 예제

'김용환' 2017. 5. 25. 19:34


이 코드는 zipWithIndex와 for-yield 문, if문을 잘 설명하는 코드이다. 


scala> def occurrencesOf[A](elem:A, collection:List[A]):List[Int] = {

     |   for {

     |     (currentElem, index) <- collection.zipWithIndex

     |     if (currentElem == elem)

     |   } yield index

     | }

occurrencesOf: [A](elem: A, collection: List[A])List[Int]


scala>


scala> occurrencesOf(10, List(0,1,2,3,4,10))

res0: List[Int] = List(5)




occurrencesOf(10, List(0,1,2,3,4,10)) 코드를 설명한다.


collection.zipWithIndex 은 다음과 같은 값을 리턴한다.


((List(0), 0), (List(1), 1), (List(2), 2), (List(3), 3), (List(4), 4), (List(10), 10))


그러다다 elem으로 들어온 10 값을 만나면 관련 index 값 10을 리턴한다.