SlideShare a Scribd company logo
-Functionalλ
Programming
with Scala
©2013 Raymond Tay
About m(e)
I write code.
I write books too !
Functional programming with_scala
https://github.com/raygit/Introduction_to_Scala
The Whats and Whos
Is Scala a fad?
This is when i first heard of Scala
Mutability
val x = 3
var y = 3
Mutability?scala> val x = mutable.HashMap[String,String]()
x: scala.collection.mutable.HashMap[String,String] = Map()
scala> x += ("a" "a")→
res0: x.type = Map(a -> a)
------
scala> val y = immutable.HashMap[String,String]()
y: scala.collection.immutable.HashMap[String,String] = Map()
scala> y += ("a" "a")→
<console>:9: error: reassignment to val
y += ("a" "a")→
Free of side effects
• Code reuse
• Make better building blocks
• Easier to reason about, optimize and test
Functions are First-classdef multiplyFour : Int Int = (4 * )⇒
def addTwo: Int Int = (2 + )⇒
def º[A,B,C](f:A B, g : B C ) = f andThen g // Parametric-⇒ ⇒
polymorphism
def f = º(multiplyFour , addTwo) // We’ll make it look more ‘natural’
in the section: Typeclasses
f(4)
res6: Int = 18
(addTwo compose multiplyFour)(4)
res4: Int = 18
Closure
val x = 3 // what if its `var x = 3`?
def = (y: Int) x + yλ ⇒
Be careful what you `close` over i.e. context-
sensitive
val xval x λλ33
var xvar x λλ33
77
Lambdas
def g( : Int Int) =λ ⇒ λ
g((x:Int) x * 2)⇒ OK
g( (x:Int) (y:Int) x + y )⇒ ⇒ FAIL
g( ((x: Int) (y: Int) x + y)(4) )⇒ ⇒ OK
Matching
// simulate a binary tree
sealed trait Tree
case class Branch(ele: Int, left:Tree: right:Tree) extends Tree
case object Leaf extends Tree
// inOrder aka Depth-First Traversal
def inOrder(t:Tree) : List[Int] = t match {
case Branch(ele, l, r) inOrder(l):::List(ele):::inOrder(r)⇒
case Leaf Nil⇒
}
Recursion
def string2spaces(ss: List[Char]) = ss match {
case Nil Nil⇒
case h :: tail ‘ ‘ :: string2spaces(tail)⇒
}
import scala.annotation.tailrec
@tailrec
def string2spaces(ss: List[Char], acc: List[Char]): List[Char] = ss match {
case Nil acc⇒
case h :: tail string2spaces(tail,‘ ‘ +: acc)⇒
}
Lazy vs Eager Eval
def IamEager[A](value:A)
def IamLazy[A](value: ⇒ A)
TypeclassesWhat I really want to write is
(addTwo ∘ multiplyFour)(4) and not
(addTwo compose multiplyFour)(4)
typeclasses - create higher kinded types! e.g.
List[Int Int]⇒
Typeclasses in Scala
trait Fn extends (Int Int) {⇒
def apply(x: Int) : Int
def º(f: Fn) = f andThen this
}
def addTwo = new Fn { def apply(x: Int) = 2 + x }
def multiplyFour = new Fn { def apply(x: Int) = 4 * x }
multiplyFour º addTwo
res0: Int => Int = <function1>
(addTwo º multiplyFour)(4)
res1: Int = 18
Typeclasses in Scala
sealed trait MList[+A]
case object Nil extends MList[Nothing]
case class ::[+A](head:A, tail: MList[A]) extends
MList[A]
object MList {
def apply[A](xs:A*) : MList[A] = if (xs.isEmpty) Nil
else ::(xs.head, apply(xs.tail: _*))
}
Typeclasses in Scala
object Main extends App {
val x = MList(1,2,3,4,5) match {
case ::(x, ::(2, ::(4, _))) => x
case Nil => 42
case ::(x, ::(y, ::(3, ::(4, _)))) => x + y
case ::(h, t) => h
case _ => 101
}
println(s"value of ${x}")
}
Adhoc Polymorphism
scala> (1,2,3) map { 1 + _ }
<console>:8: error: value map is not a member of (Int,
Int, Int)
(1,2,3) map { 1 + _ }
scala> implicit def giveMeMap[A](t : Tuple3[A,A,A]) =
new Tuple3[A,A,A](t._1, t._2, t._3) {
def map[B](f: A => B) = new Tuple3(f(_1), f(_2), f(_3))
}
scala> (1,2,3) map { 1 + _ }res1: (Int, Int, Int) = (2,3,4)
Adhoc Concurrency
class Matrix(val repr:Array[Array[Double]])
trait ThreadStrategy {
def execute[A](f: () A) : () A⇒ ⇒
}
object SingleThreadStrategy extends ThreadStrategy { //
uses a single thread }
object ThreadPoolStrategy extends ThreadStrategy { //
uses a thread pool }
Adhoc Concurrency
scala> val m = new Matrix(Array(Array(1.2, 2.2),Array(3.4, 4.5)))
m: Matrix =
Matrix
|1.2 | 2.2|
|3.4 | 4.5|
scala> val n = new Matrix(Array(Array(1.2, 2.2),Array(3.4, 4.5)))
n: Matrix =
Matrix
|1.2 | 2.2|
|3.4 | 4.5|
Adhoc Concurrency
scala> MatrixUtils.multiply(m, n)
res1: Matrix =
Matrix
|8.92 | 12.540000000000001|
|19.38 | 27.73|
scala> MatrixUtils.multiply(m, n)(ThreadPoolStrategy)
Executing function on thread: 38
Executing function on thread: 39
Executing function on thread: 40
Executing function on thread: 41
Concurrency on
Collections!
par
val parList = (1 to 1000000).toList.par
(1 to 1000000).toList.par.partition{ _ % 2 == 0 }
Functional Data
Structures - List
def foldRight[A,B](l: List[A], z: B)(f: (A,B) B) : B = l match {⇒
case Nil z⇒
case ::(h, t) f(h, foldRight(t,z)(f))⇒
}
@tailrec
def foldLeft[A,B](l: List[A], z: B)(f: (B,A) B) : B = l match {⇒
case Nil z⇒
case ::(h, t) => foldLeft(t, f(z,h))(f)
}
Reactive Concurrency
If i had more time...
• Existential Types
• Self Types
• Structural Typing (think Duck Typing)
• Compile-time metaprogramming
(macros,quasiquotes)
• Reactive Programming through Akka
• Monoids, Monads, Endos, Corecursive and a
whole lot more
Thanks
twitter: @RaymondTayBL

More Related Content

What's hot (16)

Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
Knoldus Inc.
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
Skills Matter
 
Scala Parallel Collections
Scala Parallel CollectionsScala Parallel Collections
Scala Parallel Collections
Aleksandar Prokopec
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1
Philip Schwarz
 
Python list
Python listPython list
Python list
Prof. Dr. K. Adisesha
 
Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’
Philip Schwarz
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
Johan Tibell
 
Lec4
Lec4Lec4
Lec4
Nikhil Chilwant
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
Prof. Dr. K. Adisesha
 
20170509 rand db_lesugent
20170509 rand db_lesugent20170509 rand db_lesugent
20170509 rand db_lesugent
Prof. Wim Van Criekinge
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...
Philip Schwarz
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
John Cant
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
Knoldus Inc.
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
Skills Matter
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1
Philip Schwarz
 
Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’ Addendum to ‘Monads do not Compose’
Addendum to ‘Monads do not Compose’
Philip Schwarz
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
Johan Tibell
 
Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...Scala collection methods flatMap and flatten are more powerful than monadic f...
Scala collection methods flatMap and flatten are more powerful than monadic f...
Philip Schwarz
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
John Cant
 

Similar to Functional programming with_scala (20)

Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
Damian Jureczko
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
Constantine Nosovsky
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
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
gabalese
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
djspiewak
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
Nehal Shah
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
Hang Zhao
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Innar Made
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
Damian Jureczko
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
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
gabalese
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
djspiewak
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
Nehal Shah
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
Hang Zhao
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Innar Made
 
Ad

More from Raymond Tay (8)

Principled io in_scala_2019_distribution
Principled io in_scala_2019_distributionPrincipled io in_scala_2019_distribution
Principled io in_scala_2019_distribution
Raymond Tay
 
Building a modern data platform with scala, akka, apache beam
Building a modern data platform with scala, akka, apache beamBuilding a modern data platform with scala, akka, apache beam
Building a modern data platform with scala, akka, apache beam
Raymond Tay
 
Practical cats
Practical catsPractical cats
Practical cats
Raymond Tay
 
Toying with spark
Toying with sparkToying with spark
Toying with spark
Raymond Tay
 
Distributed computing for new bloods
Distributed computing for new bloodsDistributed computing for new bloods
Distributed computing for new bloods
Raymond Tay
 
Introduction to cuda geek camp singapore 2011
Introduction to cuda   geek camp singapore 2011Introduction to cuda   geek camp singapore 2011
Introduction to cuda geek camp singapore 2011
Raymond Tay
 
Introduction to Erlang
Introduction to ErlangIntroduction to Erlang
Introduction to Erlang
Raymond Tay
 
Introduction to CUDA
Introduction to CUDAIntroduction to CUDA
Introduction to CUDA
Raymond Tay
 
Principled io in_scala_2019_distribution
Principled io in_scala_2019_distributionPrincipled io in_scala_2019_distribution
Principled io in_scala_2019_distribution
Raymond Tay
 
Building a modern data platform with scala, akka, apache beam
Building a modern data platform with scala, akka, apache beamBuilding a modern data platform with scala, akka, apache beam
Building a modern data platform with scala, akka, apache beam
Raymond Tay
 
Toying with spark
Toying with sparkToying with spark
Toying with spark
Raymond Tay
 
Distributed computing for new bloods
Distributed computing for new bloodsDistributed computing for new bloods
Distributed computing for new bloods
Raymond Tay
 
Introduction to cuda geek camp singapore 2011
Introduction to cuda   geek camp singapore 2011Introduction to cuda   geek camp singapore 2011
Introduction to cuda geek camp singapore 2011
Raymond Tay
 
Introduction to Erlang
Introduction to ErlangIntroduction to Erlang
Introduction to Erlang
Raymond Tay
 
Introduction to CUDA
Introduction to CUDAIntroduction to CUDA
Introduction to CUDA
Raymond Tay
 
Ad

Recently uploaded (20)

Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
Edge AI and Vision Alliance
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
Edge AI and Vision Alliance
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 

Functional programming with_scala

  • 2. About m(e) I write code. I write books too !
  • 6. Is Scala a fad? This is when i first heard of Scala
  • 7. Mutability val x = 3 var y = 3
  • 8. Mutability?scala> val x = mutable.HashMap[String,String]() x: scala.collection.mutable.HashMap[String,String] = Map() scala> x += ("a" "a")→ res0: x.type = Map(a -> a) ------ scala> val y = immutable.HashMap[String,String]() y: scala.collection.immutable.HashMap[String,String] = Map() scala> y += ("a" "a")→ <console>:9: error: reassignment to val y += ("a" "a")→
  • 9. Free of side effects • Code reuse • Make better building blocks • Easier to reason about, optimize and test
  • 10. Functions are First-classdef multiplyFour : Int Int = (4 * )⇒ def addTwo: Int Int = (2 + )⇒ def º[A,B,C](f:A B, g : B C ) = f andThen g // Parametric-⇒ ⇒ polymorphism def f = º(multiplyFour , addTwo) // We’ll make it look more ‘natural’ in the section: Typeclasses f(4) res6: Int = 18 (addTwo compose multiplyFour)(4) res4: Int = 18
  • 11. Closure val x = 3 // what if its `var x = 3`? def = (y: Int) x + yλ ⇒ Be careful what you `close` over i.e. context- sensitive val xval x λλ33 var xvar x λλ33 77
  • 12. Lambdas def g( : Int Int) =λ ⇒ λ g((x:Int) x * 2)⇒ OK g( (x:Int) (y:Int) x + y )⇒ ⇒ FAIL g( ((x: Int) (y: Int) x + y)(4) )⇒ ⇒ OK
  • 13. Matching // simulate a binary tree sealed trait Tree case class Branch(ele: Int, left:Tree: right:Tree) extends Tree case object Leaf extends Tree // inOrder aka Depth-First Traversal def inOrder(t:Tree) : List[Int] = t match { case Branch(ele, l, r) inOrder(l):::List(ele):::inOrder(r)⇒ case Leaf Nil⇒ }
  • 14. Recursion def string2spaces(ss: List[Char]) = ss match { case Nil Nil⇒ case h :: tail ‘ ‘ :: string2spaces(tail)⇒ } import scala.annotation.tailrec @tailrec def string2spaces(ss: List[Char], acc: List[Char]): List[Char] = ss match { case Nil acc⇒ case h :: tail string2spaces(tail,‘ ‘ +: acc)⇒ }
  • 15. Lazy vs Eager Eval def IamEager[A](value:A) def IamLazy[A](value: ⇒ A)
  • 16. TypeclassesWhat I really want to write is (addTwo ∘ multiplyFour)(4) and not (addTwo compose multiplyFour)(4) typeclasses - create higher kinded types! e.g. List[Int Int]⇒
  • 17. Typeclasses in Scala trait Fn extends (Int Int) {⇒ def apply(x: Int) : Int def º(f: Fn) = f andThen this } def addTwo = new Fn { def apply(x: Int) = 2 + x } def multiplyFour = new Fn { def apply(x: Int) = 4 * x } multiplyFour º addTwo res0: Int => Int = <function1> (addTwo º multiplyFour)(4) res1: Int = 18
  • 18. Typeclasses in Scala sealed trait MList[+A] case object Nil extends MList[Nothing] case class ::[+A](head:A, tail: MList[A]) extends MList[A] object MList { def apply[A](xs:A*) : MList[A] = if (xs.isEmpty) Nil else ::(xs.head, apply(xs.tail: _*)) }
  • 19. Typeclasses in Scala object Main extends App { val x = MList(1,2,3,4,5) match { case ::(x, ::(2, ::(4, _))) => x case Nil => 42 case ::(x, ::(y, ::(3, ::(4, _)))) => x + y case ::(h, t) => h case _ => 101 } println(s"value of ${x}") }
  • 20. Adhoc Polymorphism scala> (1,2,3) map { 1 + _ } <console>:8: error: value map is not a member of (Int, Int, Int) (1,2,3) map { 1 + _ } scala> implicit def giveMeMap[A](t : Tuple3[A,A,A]) = new Tuple3[A,A,A](t._1, t._2, t._3) { def map[B](f: A => B) = new Tuple3(f(_1), f(_2), f(_3)) } scala> (1,2,3) map { 1 + _ }res1: (Int, Int, Int) = (2,3,4)
  • 21. Adhoc Concurrency class Matrix(val repr:Array[Array[Double]]) trait ThreadStrategy { def execute[A](f: () A) : () A⇒ ⇒ } object SingleThreadStrategy extends ThreadStrategy { // uses a single thread } object ThreadPoolStrategy extends ThreadStrategy { // uses a thread pool }
  • 22. Adhoc Concurrency scala> val m = new Matrix(Array(Array(1.2, 2.2),Array(3.4, 4.5))) m: Matrix = Matrix |1.2 | 2.2| |3.4 | 4.5| scala> val n = new Matrix(Array(Array(1.2, 2.2),Array(3.4, 4.5))) n: Matrix = Matrix |1.2 | 2.2| |3.4 | 4.5|
  • 23. Adhoc Concurrency scala> MatrixUtils.multiply(m, n) res1: Matrix = Matrix |8.92 | 12.540000000000001| |19.38 | 27.73| scala> MatrixUtils.multiply(m, n)(ThreadPoolStrategy) Executing function on thread: 38 Executing function on thread: 39 Executing function on thread: 40 Executing function on thread: 41
  • 24. Concurrency on Collections! par val parList = (1 to 1000000).toList.par (1 to 1000000).toList.par.partition{ _ % 2 == 0 }
  • 25. Functional Data Structures - List def foldRight[A,B](l: List[A], z: B)(f: (A,B) B) : B = l match {⇒ case Nil z⇒ case ::(h, t) f(h, foldRight(t,z)(f))⇒ } @tailrec def foldLeft[A,B](l: List[A], z: B)(f: (B,A) B) : B = l match {⇒ case Nil z⇒ case ::(h, t) => foldLeft(t, f(z,h))(f) }
  • 27. If i had more time... • Existential Types • Self Types • Structural Typing (think Duck Typing) • Compile-time metaprogramming (macros,quasiquotes) • Reactive Programming through Akka • Monoids, Monads, Endos, Corecursive and a whole lot more