 # Functions

Like any great FP language, Scala has lots of built-in functions. These functions make our code more fluent and functional; now it's time to learn some of these functions:

\$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help.

scala>// Creates the numbers 1,2,3,4,5 and them multiply they by 2 and

creates a new Vector

scala>println ((1 to 5).map(_*2))

Vector(2, 4, 6, 8, 10) scala>

scala>// Creates 1,2,3 and sum them all with each orher and return the total

scala>println ( (1 to 3).reduceLeft(_+_) )

6

scala>

scala>// Creates 1,2,3 and multiply each number by it self and return a Vector

scala>println ( (1 to 3).map( x=> x*x ) )

Vector(1, 4, 9) scala>

scala>// Creates numbers 1,2,3,4 ans 5 filter only Odd numbers them multiply them odds by 2 and return a Vector

scala>println ( (1 to 5) filter { _%2 == 0 } map { _*2 } )

Vector(4, 8) scala>

scala>// Creates a List with 1 to 5 and them print each element being multiplyed by 2

scala>List(1,2,3,4,5).foreach ( (i:Int) => println(i * 2 ) )

• 2
• 4
• 6
• 8
• 10

Introduction to FP, Reactive, and Scala

scala>

scala>// Creates a List with 1 to 5 and then print each element being multiplied by 2

scala>List(1,2,3,4,5).foreach ( i => println(i * 2) )

• 2
• 4
• 6
• 8
• 10

scala>

scala>// Drops 3 elements from the lists scala>println( List(2,3,4,5,6).drop(3))

List(5, 6)

scala>println( List(2,3,4,5,6) drop 3 )

List(5, 6) scala>

scala>// Zip 2 lists into a single one: It will take 1 element of each list and create a pair List

scala>println( List(1,2,3,4).zip( List(6,7,8) ))

List((1,6), (2,7), (3,8))

scala>

scala>// Take nested lists and create a single list with flat elements scala>println( List(List(1, 2), List(3, 4)).flatten )

List(1, 2, 3, 4) scala>

scala>// Finds a person in a List by Age scala>case class Person(age:Int,name:String) defined class Person

scala>println( List(Person(31,"Diego"),Person(40,"Nilseu")).find( (p:Person) => p.age <= 33 ) )

Some(Person(31,Diego))

scala> 