SlideShare a Scribd company logo
1 of 22
Scala training workshop 01
Nguyen Thanh Tuan
Platform Department
@Septeni Technology
Agenda
- Summary
- Functions & Evaluations
- Higher Order Functions
- Data and Abstraction
- Exercise
- Share
Functions & Evaluations
- Conditionals and Value Definitions
- Blocks
- Tail recursion
Conditional and Value Definition
- Sample :
val <identifier>[: <type>] = <expression>
var <identifier>[: <type>] = <expression>
- If Expressions
if (<Boolean expression>) <expression>
- If-Else Expressions
if (<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
Example
- If Expressions
if (10%2 == 0) println(“10 is a multiple of 2”)
- If-Else Expressions
val x = 10;
val y = 5
if (x > y) println(“Max number is :”+ x)
else println(“Max numner is :” + y)
- Match Expressions
val 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 Patterns
case _ => {println(s”Couldn’t parse $message”) -1}
- Matching with Pattern Guards
case 3 if 3 > 5=> println(“Something”)
Source : Safaribooksonline.com
Blocks
val 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.
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)
Example
def 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)
}
Tail&Head recursion in Scala
def 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 ) )
Higher-order function
- Higher Order Functions
- Currying
Higher-order function
Scala allows the definition of higher-order
functions.
- Functions can take other functions as
parameters
- Result is a function
- Example
Example higherOrder
object 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() + "]
}
Currying Functions
Currying 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
Example Currying functions
object 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
}
}
Data and Abstraction
- Class hierarchy
- Trait and Abstractclass
Class hierarchy
Source : meetfp.com
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)
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
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
Exercises
object 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)
}
}
}
Shares
Thank for comming

More Related Content

What's hot

A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaDerek Chen-Becker
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in ScalaRose Toomey
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapDave Orme
 
Android course session 5 (Threads & socket)
Android course session 5 (Threads & socket)Android course session 5 (Threads & socket)
Android course session 5 (Threads & socket)Keroles M.Yakoub
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Javaagorolabs
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
Java 101 Intro to Java Programming - Exercises
Java 101   Intro to Java Programming - ExercisesJava 101   Intro to Java Programming - Exercises
Java 101 Intro to Java Programming - Exercisesagorolabs
 

What's hot (11)

A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Simplicitly
SimplicitlySimplicitly
Simplicitly
 
Android course session 5 (Threads & socket)
Android course session 5 (Threads & socket)Android course session 5 (Threads & socket)
Android course session 5 (Threads & socket)
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Java
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Java 101 Intro to Java Programming - Exercises
Java 101   Intro to Java Programming - ExercisesJava 101   Intro to Java Programming - Exercises
Java 101 Intro to Java Programming - Exercises
 
Scale up your thinking
Scale up your thinkingScale up your thinking
Scale up your thinking
 

Similar to Scala basic

Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02Nguyen Tuan
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaAyush Mishra
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in ScalaAyush Mishra
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in rmanikanta361
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 

Similar to Scala basic (20)

Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 

Recently uploaded

Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

Scala basic

  • 1. Scala training workshop 01 Nguyen Thanh Tuan Platform Department @Septeni Technology
  • 2. Agenda - Summary - Functions & Evaluations - Higher Order Functions - Data and Abstraction - Exercise - Share
  • 3. Functions & Evaluations - Conditionals and Value Definitions - Blocks - Tail recursion
  • 4. Conditional and Value Definition - Sample : val <identifier>[: <type>] = <expression> var <identifier>[: <type>] = <expression> - If Expressions if (<Boolean expression>) <expression> - If-Else Expressions if (<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
  • 5. Example - If Expressions if (10%2 == 0) println(“10 is a multiple of 2”) - If-Else Expressions val x = 10; val y = 5 if (x > y) println(“Max number is :”+ x) else println(“Max numner is :” + y) - Match Expressions val 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 Patterns case _ => {println(s”Couldn’t parse $message”) -1} - Matching with Pattern Guards case 3 if 3 > 5=> println(“Something”) Source : Safaribooksonline.com
  • 6. Blocks val 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.
  • 7. 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)
  • 8. Example def 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) }
  • 9. Tail&Head recursion in Scala def 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 ) )
  • 10. Higher-order function - Higher Order Functions - Currying
  • 11. Higher-order function Scala allows the definition of higher-order functions. - Functions can take other functions as parameters - Result is a function - Example
  • 12. Example higherOrder object 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() + "] }
  • 13. Currying Functions Currying 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
  • 14. Example Currying functions object 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 } }
  • 15. Data and Abstraction - Class hierarchy - Trait and Abstractclass
  • 17. 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)
  • 18. 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
  • 19. 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
  • 20. Exercises object 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) } } }

Editor's Notes

  1. https://www.safaribooksonline.com/library/view/learning-scala/9781449368814/ch03.html
  2. http://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/slides/week1-6-no-annot.pdf
  3. There are two basic kinds of recursive: head recursive and tail recursive. In head recursion and tail recursion. In head recursion, a function makes its recursive call and then performs some more calculations, maybe using the result of the recursive call. In a tail recursive function, all calculations happen first and the recursive call is the last thing that happens This won’t work with head recursive. Because : First it does some work, then it makes its recursive call, then it does a little more work. We can’t just re-use the current stack frame when we make that recursive call. We’re going to NEED that stack frame into after the recursive call completes
  4. http://oldfashionedsoftware.com/2008/09/27/tail-recursion-basics-in-scala/
  5. http://meetfp.com/en/scala-basic/class-hierarchy http://www.artima.com/pins1ed/scalas-hierarchy.html Any is the top class, which means, every other class inherits from Any, therefor every object can invoke methods provided by Any. Those methods are as following. Null is a subtype of all reference type, and Nothing is a subtype of all other classes The root class Any has two subclasses: AnyVal and AnyRef. AnyVal is the parent class of every built-in value class in Scala. There are nine such value classes: Byte,Short, Char, Int, Long, Float, Double, Boolean, and Unit. The first eight of these correspond to Java's primitive types, and their values are represented at run time as Java's primitive values. The instances of these classes are all written as literals in Scala. For example, 42 is an instance of Int, 'x' is an instance of Char, and false an instance ofBoolean. You cannot create instances of these classes using new. This is enforced by the "trick" that value classes are all defined to be both abstract and final The other subclass of the root class Any is class AnyRef. This is the base class of all reference classes in Scala. As mentioned previously, on the Java platform AnyRef is in fact just an alias for class java.lang.Object. So classes written in Java as well as classes written in Scala all inherit from AnyRef.[1] One way to think of java.lang.Object, therefore, is as the way AnyRef is implemented on the Java platform. Thus, although you can use Object and AnyRef interchangeably in Scala programs on the Java platform, the recommended style is to use AnyRef everywhere. Class Null is the type of the null reference; it is a subclass of every reference class (i.e., every class that itself inherits from AnyRef). Null is not compatible with value types.You cannot, for example, assign a null value to an integer variable: scala> val i: Int = null <console>:4: error: type mismatch; found : Null(null) required: Int Type Nothing is at the very bottom of Scala's class hierarchy; it is a subtype of every other type. However, there exist no values of this type whatsoever. Why does it make sense to have a type without values? As discussed in Section 7.4, one use of Nothing is that it signals abnormal termination. For instance there's the error method in thePredef object of Scala's standard library, which is defined like this: def error(message: String): Nothing = throw new RuntimeException(message)
  6. If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class. The issue is that when a trait gains or loses a member, any classes that inherit from it must be recompiled, even if they have not changed. If outside clients will only call into the behavior, instead of inheriting from it, then using a trait is fine.
  7. http://alvinalexander.com/scala/scala-trait-examples