Wednesday 17 June 2009

You can use loops instead of compex maps

For example:

Using this 'for' loop the 'yield' function acts like a flatmap:

def loopMe() = {
val numbers = for( i <- 1 to 10; if i % 2 == 0;
j <- i to 10 if j % 2 == 1) yield i * j
println(numbers)
}


Here is the equivalent with traditional maps and filters:

def mapMe() = {
val num2 = (1 to 10).filter( a => a % 2 == 0)
val num3 = num2.flatMap( a => (a to 10).filter(b => b % 2 == 1).map(c => c * a ) )

println(num3)
}

No comments:

Post a Comment