Scala basic

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

Transcript of Scala basic

Page 1: Scala basic

Scala training workshop 01

Nguyen Thanh TuanPlatform Department@Septeni Technology

Page 2: Scala basic

Agenda- Summary

- Functions & Evaluations- Higher Order Functions- Data and Abstraction

- Exercise- Share

Page 3: Scala basic

Functions & Evaluations- Conditionals and Value Definitions- Blocks- Tail recursion

Page 4: Scala basic

Conditional and Value Definition- Sample :

val <identifier>[: <type>] = <expression>var <identifier>[: <type>] = <expression>

- If Expressionsif (<Boolean expression>) <expression>

- If-Else Expressionsif (<Boolean expression>) <expression>else <expression>

- Match Expressions<expression> match { case <pattern match> => <expression> [case...]}

- A Pattern Alternative :case <pattern 1> | <pattern 2> .. => <one or more

expressions>- Matching with Wildcard Patterns

case <identifier> => <one or more expressions>- Matching with Pattern Guards

case <pattern> if <Boolean expression> => <one or more expressions>

- Match Expressions<expression> match { case <pattern match> => <expression> [case...]}

Source : Safaribooksonline.com

Page 5: Scala basic

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 basic

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 basic

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 basic

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 basic

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 basic

Higher-order function- Higher Order Functions- Currying

Page 11: Scala basic

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 basic

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 basic

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 basic

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 basic

Data and Abstraction- Class hierarchy- Trait and Abstractclass

Page 16: Scala basic

Class hierarchy

Source : meetfp.com

Page 17: Scala basic

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 basic

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 basic

Exercises - Pascal’s Triangle

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

1

1 1

1 2 1

1 3 3 1

1 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 basic

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 basic

Shares

Page 22: Scala basic

Thank for comming