# For-Comprehension and Effects Combination

• display list
``````for{
e <- elements
} println(e)  //no yield

elements foreach println
``````

*good example with files

`````` val filesHere = (new File(".")).listFiles()

for (file <- filesHere)
println(file)

for(i <-1 to 100) println(i)
``````
• map list
• zwrócić uwagę na typ rezultatu! (Lista dla Listy, Vector dla Vector, Option dla Option)
``````for{
e <- elements
} yield f(e)

elements map f
``````
• flatMap list
``````for{
e1 <- elements
e2 <- otherElements
} yield f(e1,e2)

elements.flatMap(e1=>otherelements.map(e2=>f(e1,e2)))
``````
• definitions
``````for{
e1 <- elements
val value="aaa"
e2 <- otherElements
} yield f(e1,e2,value)

e1.flatMap{e1 =>
val value="aaa"
otherElements.map(e2=>f(e1,e2,value))
}
``````
• guard
``````
for {
e <- elements
if f(e)
} yield f2(e)

elements.withFilter(f(e)).map(f2(e))
``````

## Deeper

• Pattern Matching
``````pat <- expr.withFilter { case pat => true; case _ => false }

// for ( pat <- expr1 ) yield expr2
expr map { case pat => expr2 }
expr1 flatMap { case pat1 => for (pat2 <- expr2 ...) yield exprN }
``````

## Option

``````val results2 = for {
Some(i) <- results
} yield (2 * i)

withFilter{case (Some(i)) => true; case _ => false}
``````
• Either,
``````val l2: String Either Int = Left("infix")
//projections
l.right.map(_.toDouble)
``````
• Try, Validation
• flatten