Tuesday, November 17, 2015

Scala map vs flatMap

map is loop thru all element and apply a function into it.
scala> val i = List("Apple", "Banana", "Orange")
i: List[String] = List(Apple, Banana, Orange)

scala> i.map(x => x.toUpperCase)
res2: List[Char] = List(APPLE, BANANA, ORANGE)
flatMap is loop thru all element, flatten the element and apply a function into it.
scala> val i = List("Apple", "Banana", "Orange")
i: List[String] = List(Apple, Banana, Orange)

scala> i.flatMap(x => x.toUpperCase)
res2: List[Char] = List(A, P, P, L, E, B, A, N, A, N, A, O, R, A, N, G, E)
Here is an example on different between map and flatMap in List(List(), List())
scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)

scala> def x(v:Int) = List(v,v+1)
x: (v: Int)List[Int]

scala> l.map(i => x(i))
res5: List[List[Int]] = List(List(1, 2), List(2, 3), List(3, 4))

scala> l.flatMap(i => x(i))
res6: List[Int] = List(1, 2, 2, 3, 3, 4)
Here is an example on different between map and flatMap in Option (None and Some). flatMap remove empty value (None).
scala> val l = List(1,2,3,4,5)
l: List[Int] = List(1, 2, 3, 4, 5)

scala> def f(x:Int) = if (x > 2) Some(x) else None
f: (x: Int)Option[Int]

scala> l.map( x => f(x))
res11: List[Option[Int]] = List(None, None, Some(3), Some(4), Some(5))

scala> l.flatMap( x => f(x))
res12: List[Int] = List(3, 4, 5)
References:
http://www.brunton-spall.co.uk/post/2011/12/02/map-map-and-flatmap-in-scala/
http://alvinalexander.com/scala/collection-scala-flatmap-examples-map-flatten

Sunday, November 15, 2015

Scala For Loop Syntax

For Loop with Counter

The simplest loop syntax is:
for (a  <- 1 to 5){
   println(“Print a: ” + a);
}

When the above code is compiled and executed, it produces following result:
Print a: 1
Print a: 2
Print a: 3
Print a: 4
Print a: 5
By default, counter increment is 1. You can change the number of counter increment using "by".
for (a  <- 1 to 5 by 2) {
   println(“Print a: ” + a);
}
When the above code is compiled and executed, it produces following result:
Print a: 1
Print a: 3
Print a: 5

For Loop with Filter

You can filter out some of the elements. Following is the example of for loop along with filters:
for (
   a  <- 1 to 5
   if ( a > 3)
) {
   println(“Print a: ” + a);
}
When the above code is compiled and executed, it produces following result:
Print a: 4
Print a: 5

For Loop with Yield

This is one of the awesome feature in Scala where you generate a static type variable using loop. I don’t really see in other programming language.

When For loop finishes running, it returns a collection of all these yielded values.

The type of the collection that is returned is the same type that you were iterating over.

// Loop through and generate a variable
val i = for (
   a  <- 1 to 5
   if ( a > 3)
) yield {
   a
}

// Print the result
for( a <- i){
   println( "Value of a: " + a );
}
When the above code is compiled and executed, it produces following result:
Print a: 4
Print a: 5