SlideShare a Scribd company logo
1 of 22
Scala training workshop 02
Nguyen Thanh Tuan
Platform Department
@Septeni Technology
Agenda
- Summary
- Types and Pattern Matching
- Lists
- Collections
- Lazy Evaluation
- Exercise
- Share
Types and Pattern Matching
- Functions as Objects
- Subtyping and Generics
- Objectis Everywhere
- Variance
- Decomposition
- Pattern Matching
- Lists
Functions as Objects
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

Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In ScalaKnoldus Inc.
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scalaRaymond Tay
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and FuturePushkar Kulkarni
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkAngelo Leto
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectivegabalese
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idrisConor Farrell
 

What's hot (19)

Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Lec3
Lec3Lec3
Lec3
 
ScalaBlitz
ScalaBlitzScalaBlitz
ScalaBlitz
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idris
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Lec2
Lec2Lec2
Lec2
 

Viewers also liked

IndexedRDD: Efficeint Fine-Grained Updates for RDD's-(Ankur Dave, UC Berkeley)
IndexedRDD: Efficeint Fine-Grained Updates for RDD's-(Ankur Dave, UC Berkeley)IndexedRDD: Efficeint Fine-Grained Updates for RDD's-(Ankur Dave, UC Berkeley)
IndexedRDD: Efficeint Fine-Grained Updates for RDD's-(Ankur Dave, UC Berkeley)Spark Summit
 
What’s New in the Berkeley Data Analytics Stack
What’s New in the Berkeley Data Analytics StackWhat’s New in the Berkeley Data Analytics Stack
What’s New in the Berkeley Data Analytics StackTuri, Inc.
 
What's New in Spark 2?
What's New in Spark 2?What's New in Spark 2?
What's New in Spark 2?Eyal Ben Ivri
 
Advanced Analytics and Recommendations with Apache Spark - Spark Maryland/DC ...
Advanced Analytics and Recommendations with Apache Spark - Spark Maryland/DC ...Advanced Analytics and Recommendations with Apache Spark - Spark Maryland/DC ...
Advanced Analytics and Recommendations with Apache Spark - Spark Maryland/DC ...Chris Fregly
 
YARN Ready: Apache Spark
YARN Ready: Apache Spark YARN Ready: Apache Spark
YARN Ready: Apache Spark Hortonworks
 
Electronic governance steps in the right direction?
Electronic governance   steps in the right direction?Electronic governance   steps in the right direction?
Electronic governance steps in the right direction?Bozhidar Bozhanov
 
Low Latency Execution For Apache Spark
Low Latency Execution For Apache SparkLow Latency Execution For Apache Spark
Low Latency Execution For Apache SparkJen Aman
 
Hortonworks Technical Workshop: HBase For Mission Critical Applications
Hortonworks Technical Workshop: HBase For Mission Critical ApplicationsHortonworks Technical Workshop: HBase For Mission Critical Applications
Hortonworks Technical Workshop: HBase For Mission Critical ApplicationsHortonworks
 
G.C.E O/L ICT Short Notes Grade-11
G.C.E O/L ICT Short Notes Grade-11G.C.E O/L ICT Short Notes Grade-11
G.C.E O/L ICT Short Notes Grade-11Mahesh Kodituwakku
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyBozhidar Bozhanov
 
Processing Large Data with Apache Spark -- HasGeek
Processing Large Data with Apache Spark -- HasGeekProcessing Large Data with Apache Spark -- HasGeek
Processing Large Data with Apache Spark -- HasGeekVenkata Naga Ravi
 
Introduction to Hadoop and Spark (before joining the other talk) and An Overv...
Introduction to Hadoop and Spark (before joining the other talk) and An Overv...Introduction to Hadoop and Spark (before joining the other talk) and An Overv...
Introduction to Hadoop and Spark (before joining the other talk) and An Overv...DataWorks Summit/Hadoop Summit
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 

Viewers also liked (20)

Sparkstreaming
SparkstreamingSparkstreaming
Sparkstreaming
 
Devops Spark Streaming
Devops Spark StreamingDevops Spark Streaming
Devops Spark Streaming
 
IndexedRDD: Efficeint Fine-Grained Updates for RDD's-(Ankur Dave, UC Berkeley)
IndexedRDD: Efficeint Fine-Grained Updates for RDD's-(Ankur Dave, UC Berkeley)IndexedRDD: Efficeint Fine-Grained Updates for RDD's-(Ankur Dave, UC Berkeley)
IndexedRDD: Efficeint Fine-Grained Updates for RDD's-(Ankur Dave, UC Berkeley)
 
Spark Technology Center IBM
Spark Technology Center IBMSpark Technology Center IBM
Spark Technology Center IBM
 
What’s New in the Berkeley Data Analytics Stack
What’s New in the Berkeley Data Analytics StackWhat’s New in the Berkeley Data Analytics Stack
What’s New in the Berkeley Data Analytics Stack
 
October 2014 HUG : Hive On Spark
October 2014 HUG : Hive On SparkOctober 2014 HUG : Hive On Spark
October 2014 HUG : Hive On Spark
 
What's New in Spark 2?
What's New in Spark 2?What's New in Spark 2?
What's New in Spark 2?
 
Advanced Analytics and Recommendations with Apache Spark - Spark Maryland/DC ...
Advanced Analytics and Recommendations with Apache Spark - Spark Maryland/DC ...Advanced Analytics and Recommendations with Apache Spark - Spark Maryland/DC ...
Advanced Analytics and Recommendations with Apache Spark - Spark Maryland/DC ...
 
YARN Ready: Apache Spark
YARN Ready: Apache Spark YARN Ready: Apache Spark
YARN Ready: Apache Spark
 
Electronic governance steps in the right direction?
Electronic governance   steps in the right direction?Electronic governance   steps in the right direction?
Electronic governance steps in the right direction?
 
Low Latency Execution For Apache Spark
Low Latency Execution For Apache SparkLow Latency Execution For Apache Spark
Low Latency Execution For Apache Spark
 
Hortonworks Technical Workshop: HBase For Mission Critical Applications
Hortonworks Technical Workshop: HBase For Mission Critical ApplicationsHortonworks Technical Workshop: HBase For Mission Critical Applications
Hortonworks Technical Workshop: HBase For Mission Critical Applications
 
G.C.E O/L ICT Short Notes Grade-11
G.C.E O/L ICT Short Notes Grade-11G.C.E O/L ICT Short Notes Grade-11
G.C.E O/L ICT Short Notes Grade-11
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very ugly
 
Processing Large Data with Apache Spark -- HasGeek
Processing Large Data with Apache Spark -- HasGeekProcessing Large Data with Apache Spark -- HasGeek
Processing Large Data with Apache Spark -- HasGeek
 
What's new in Hadoop Common and HDFS
What's new in Hadoop Common and HDFS What's new in Hadoop Common and HDFS
What's new in Hadoop Common and HDFS
 
Introduction to Hadoop and Spark (before joining the other talk) and An Overv...
Introduction to Hadoop and Spark (before joining the other talk) and An Overv...Introduction to Hadoop and Spark (before joining the other talk) and An Overv...
Introduction to Hadoop and Spark (before joining the other talk) and An Overv...
 
Apache Hadoop 3.0 What's new in YARN and MapReduce
Apache Hadoop 3.0 What's new in YARN and MapReduceApache Hadoop 3.0 What's new in YARN and MapReduce
Apache Hadoop 3.0 What's new in YARN and MapReduce
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 

Similar to Scala training workshop 02

The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
(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
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data ManagementAlbert Bifet
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in ScalaAyush Mishra
 
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
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
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
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 

Similar to Scala training workshop 02 (20)

Scala basic
Scala basicScala basic
Scala basic
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
(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?
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to 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
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
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
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
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
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 

Scala training workshop 02

  • 1. Scala training workshop 02 Nguyen Thanh Tuan Platform Department @Septeni Technology
  • 2. Agenda - Summary - Types and Pattern Matching - Lists - Collections - Lazy Evaluation - Exercise - Share
  • 3. Types and Pattern Matching - Functions as Objects - Subtyping and Generics - Objectis Everywhere - Variance - Decomposition - Pattern Matching - Lists
  • 4. Functions as Objects 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://twitter.github.io/scala_school/basics2.html http://kwangyulseo.com/2014/03/03/functions-are-objects-in-scala/
  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