카테고리 없음
[scala] For Loop : scala look
스트레스리스맨
2017. 4. 19. 11:25
Sequential Programming Language 에서 for loop 은 단순한 반복 구문이었는데 scala 에서는 좀 신기한 관점으로 바라본다. 일단 for loop 자체가 for comprehension 이라는 이름으로 통용되고 보통 다른 collection 으로의 변환이 가능하다.
Scala Language Specification 에 for loop 이 어떻게 해석되는가에 대한 내용이 있는데 이를 scala cookbook 에서 이렇게 정리했다.
- collection 에 대한 단순한 for loop 은 foreach 로 전환 가능
- guard 에 대한 for loop 은 foreach 후 collection 에 대한 withFilter 메소드 시퀀스로 전환 가능
- yield 가 첨가된 for loop 은 map 으로 전환 된다.
- yield + guard 의 for loop 은 map 호출 이후 collection 에 대한 withFilter 메소드 호출 전환가능
각각의 예제
1. Collection + Loop
for(i <- 0 until 5) println(i)
// could be translated to
1.to(5).foreach(println)
2. Collection + Guard + Loop 1
for{
i <-1 to 10
if i%2 == 0
} println(i)
//could be translated to
1.to(10).withFilter(i=> i%2 ==0).foreach(println)
3. Collection + Loop + yield
for{
i <- 1 to 10
} yield i
//could be translated to
1.to(10).map(i=> i)
4. Collection + Guard + Loop + yield
for{
i <-1 to 10
if i%2 == 0
} yield i
//could be translated to
1.to(10).withFilter(i=> i%2==0).map(i=> i)
- if statement 등 [본문으로]