Showing posts with label loop. Show all posts
Showing posts with label loop. Show all posts

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)
}

Sunday, 14 June 2009

Funky stuff with for loops & prepopulating lists

You can pre populate a list with a loop like "val list = 1 to 20"

You can return stuff from a for loop with the "yield" command

def looping() = {
val myList = (1 to 20 by 3)
println(myList)

val list2 = for( i <- myList if i % 2 == 0 ) yield i
println(list2)
}

Wednesday, 3 June 2009

Dont think loop!

When ever you want to loop thru a list returning a new list of values use map or flatmap

If you do need to loop:
for( i <- 0 until 4) {
}