Scala training workshop 02

22
Scala training workshop 02 Nguyen Thanh Tuan Platform Department @Septeni Technology

Transcript of Scala training workshop 02

Page 1: Scala training workshop 02

Scala training workshop 02

Nguyen Thanh TuanPlatform Department@Septeni Technology

Page 2: Scala training workshop 02

Agenda- Summary

- Types and Pattern Matching- Lists- Collections- Lazy Evaluation

- Exercise- Share

Page 3: Scala training workshop 02

Types and Pattern Matching- Functions as Objects- Subtyping and Generics- Objectis Everywhere- Variance- Decomposition- Pattern Matching- Lists

Page 4: Scala training workshop 02

Functions as Objects

Source : Safaribooksonline.com

Page 5: Scala training workshop 02

Example- If Expressions

if (10%2 == 0) println(“10 is a multiple of 2”)

- If-Else Expressionsval x = 10;val y = 5if (x > y) println(“Max number is :”+ x)else println(“Max numner is :” + y)

- Match Expressionsval x = 10;val y = 5;val max = x > y match { case true => x case true => y}

- A Pattern Alternative :val day = “MON”val kind = day match {

case “MON”| ”TUE” | “WED” | “THU” | “FRI” =>

“weekday”case “SAT” | “SUN” =>

“weekend”}

- Matching with Wildcard Patternscase _ => {println(s”Couldn’t parse

$message”) -1}- Matching with Pattern Guards

case 3 if 3 > 5=> println(“Something”)

Source : Safaribooksonline.com

Page 6: Scala training workshop 02

Blocksval x = 0 def f(y: Int) = y + 1 val result = {

val x = f(3) x * x

} + x

- A block is delimited by braces { ... }

- It contains a sequence of definitions or expressions

- Blocks are themselves expressions; a block may appear everywhere an expression can

- The definitions inside a block are only visible from within the block.

Page 7: Scala training workshop 02

Tail recursion- Recursion definition : A call B, B call A ..etc- Reasons we don’t see alot of recursion code in Java

- is hard ( is not intuitive : you see one layer and you have to imagine what happens when those layers stack up)

- is not designed to accommodate recursion. It’s designed to accommodate iteration.

- But in Scala, being a function language is very much geared toward recursion rather than iteration ( Scala in the case of tail recursive, can eliminate the creation of a new stack frame and just re-use the current stack frame)

Page 8: Scala training workshop 02

Exampledef pascal(c: Int, r: Int): Int = { if(c == 0) return 1 if(c == 1 && c != r) return r if(c == r) return 1 pascal(c-1,r-1)+pascal(c,r-1) }

Page 9: Scala training workshop 02

Tail&Head recursion in Scaladef listLength2(list: List[_]): Int = { def listLength2Helper(list: List[_], len: Int): Int = { if (list == Nil) len else listLength2Helper(list.tail, len + 1) } listLength2Helper(list, 0)}

var list1 = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)println( listLength2( list1 ) )

def listLength1(list: List[_]): Int = { if (list == Nil) 0 else 1 + listLength1(list.tail)} var list1 = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

println( listLength1( list1 ) )

Page 10: Scala training workshop 02

Higher-order function- Higher Order Functions

- Currying

Page 11: Scala training workshop 02

Higher-order functionScala allows the definition of higher-order functions.- Functions can take other functions as parameters

- Result is a function- Example

Page 12: Scala training workshop 02

Example higherOrderobject higherOrder { def main(args: Array[String]) {

println( apply( layout, 10) )

}

def apply(f: Int => String, v: Int) = f(v)

def layout[A](x: A) = "[" + x.toString() + "] }

Page 13: Scala training workshop 02

Currying FunctionsCurrying transforms a function that takes multiple parameters into a chain of function, each taking a single parameter. Curried functions are defined with multiple parameter lists, as follows :def strcat(s1: String)(s2: String) = s1 + s2

OR

def strcat(s1: String) = (s2: String) => s1 + s2

Page 14: Scala training workshop 02

Example Currying functionsobject Currying { def main(args: Array[String]) { val str1:String = "Hello, " val str2:String = "Scala!" println( "str1 + str2 = " + strcat(str1)(str2) ) }

def strcat(s1: String)(s2: String) = { s1 + s2 }}

Page 15: Scala training workshop 02

Data and Abstraction- Class hierarchy- Trait and Abstractclass

Page 16: Scala training workshop 02

Class hierarchy

Source : meetfp.com

Page 17: Scala training workshop 02

Trait and Abstract class- Scala has traits, and a trait is more flexible than an abstract class, so you

wonder, “When should I use an abstract class?”- Reason is :

- You want to create a base class that requires constructor arguments- The code will be called from Java code

- We can use

abstract class Animal(name: String)- But we can’t use

trait Animal(name: String)

Page 18: Scala training workshop 02

Trait ( The reason we should use trait )

- One big advantage of traits is that you can extend multiple traits but only one abstract class. Traits solve many of the problems with multiple inheritance but allow code reuse.

- Define types by specifying the signatures of supported methods. This is similar to how interfaces work in Java.

But trait can’t- Traits do not have constructor parameters (but this should not be an issue in practice).- Traits impose a slight performance overhead (but this is unlikely to impact the overall performance

of your program)- Traits introduce compilation fragility for classes that mix them in. If a trait changes, a class that

mixes it in has to be recompiled

Page 19: Scala training workshop 02

Exercises - Pascal’s Triangle

The following pattern of numbers is called Pascal’s triangle.

1 1 1 1 2 1 1 3 3 11 4 6 4 1 ...

The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. Write a function

that computes the elements of Pascal’s triangle by means of a recursive process.

Do this exercise by implementing the pascal function in Main.scala, which takes a column c and a row r, counting from 0 and returns the

number at that spot in the triangle. For example: pascal(0,2)=1, pascal(1,2)=2 and pascal(1,3)=3.

def pascal(c: Int, r: Int): Int

Source : coursera.org

Page 20: Scala training workshop 02

Exercisesobject Main { def main(args: Array[String]) { println("Pascal's Triangle") for (row <- 0 to 10) { for (col <- 0 to row) print(pascal(col, row) + " ") println() } def pascal(c: Int, r: Int): Int = {

c match { case 0 => 1 case 1 if c == 1 && c != r => r case r => 1 case _ => pascal(c-1,r-1)+pascal(c,r-1) } }}

Page 21: Scala training workshop 02

Shares

Page 22: Scala training workshop 02

Thank for comming