SlideShare a Scribd company logo
How to startHow to start
Functional ProgrammingFunctional Programming
(in Scala):Day1(in Scala):Day1
Who am I?Who am I?
Taisuke Oe (Twitter: @OE_uia, GitHub: @taisukeoe)
ScalaMatsuri organizer as a chairperson
Technical Advisor at Septeni Original, Inc.
ScalaMatsuri CFP is open now!ScalaMatsuri CFP is open now!
"Functional Programming""Functional Programming"
Functional Programming is the paradigm to construct a
software with composing computations like functions.
(in a casual de nition)
Through learning FP, you can learn the ways to make
functions or comutations smallish, composable and iducible.
That helps to keep your software clean and extensible, even
in OOP.
Scala is indeed a functional language,Scala is indeed a functional language,
butbut
not very strict about FP principles.
Scala uni es FP and OOP, and recommends to leverage both
of their strengths.
Today's topicToday's topic
Function compositions.
Function purity.
Abstracting from functions and composition.
Composing functions andComposing functions and
methods.methods.
What is a function?What is a function?
A function is a computation to transform inputs into outputs.
It's an instance of FunctionNtraits in Scala.
FunctionNmeans a function type which takes N arguments
(from 0 to 22).
Function0[T], Function1[T1,T2], ... , Function22[T1,...,T23]
Function1Function1
Int=Intis a type alias to Function1[Int,Int].
scala val double = (i:Int) = i * 2
double: Int = Int = function1
Function1 is composable.Function1 is composable.
Function1has andThenand composemethod for function
compositions.
scala val quadraple = double compose double
quadraple: Int = Int = function1
scala quadraple(3)
res0: Int = 12
Function2 to 22 don't have thoseFunction2 to 22 don't have those
methods, but...methods, but...
Function2 to 22 can be curried.Function2 to 22 can be curried.
Curryingmeans converting a multiple argument funtion to
Function1.
Currying Function2Currying Function2
Function2[Int,String,Int]is curriedto
Function1[Int,Function1[String,Int]]
scala val combine = (left:Int, right:Int) = left + right
combine: (Int, Int) = Int = function2
scala combine.curried
res0: Int = (Int = Int) = function1
Function2 to 22 can be composed viaFunction2 to 22 can be composed via
currying.currying.
Thus Function1- Function22are composable.
scala double andThen combine.curried
res0: Int = (Int = Int) = function1
FP fundamentalsFP fundamentals
As we see, functions can take another function as an
agrument or a return value.
This is to say a function is a rst class citizen.
Those functions are called higher order functions.
Above two are fundamentals in FP.
Methods and type parameterMethods and type parameter
Di erence from functionsDi erence from functions
Method is de ned by def keyword.
Methods can be expanded to FunctionNby _. (eta-expansion)
scala def double(i:Int):Int = i * 2
double: (i: Int)Int
scala double _
res0: Int = Int = function1
Methods can take type parameters or an implicit parameter
list, while functions cannot.
Methods with type parameterMethods with type parameter
Seq[T] has a method map[U]which modi es Ttyped elements
into Utyped elements.
def map[U](f: T = U): Seq[U]
scala Seq(1,2,3).map(_ + 1)
res0: Seq[Int] = List(2,3,4)
Combine all together.Combine all together.
Now we know function composition basics!
scala val apCurried = combine.curried
apCurried: Int = (Int = Int) = function1
// (X + 3) * 2
scala val plus3Double = apCurried(3) andThen double
plus3Double: Int = Int = function1
scala seq = Seq(1,2,3).map(plus3Double)
seq: Seq[Int] = Seq(8,10,12)
Pure FunctionsPure Functions
All functions so far are pure functions
They always return the same value with the same arguments.
Watch out side e ectsWatch out side e ects
Changing any state.
Depending on mutable state which may change.
Standard ouput
File I/O
Throwing exceptions.
All above side effects may change functions behaviour
depends on state.
What isWhat is resultresult??
var counter = 0
val next = (nth: Int) = {
counter += nth
counter
}
scala next(1)
res0: Int = 1
scala val result = (next andThen next andThen next)(3)
You have to care the order of execution and each state, even
if you compose!
It's sometimes hard to predict how impure functions behave.
scala val result = (next andThen next andThen next)(3)
result: Int = 16
localize side-e ectslocalize side-e ects
All side effects cannot be removed from your program.
The key is to localize and seperate side effects from other
functions.
Referential transparencyReferential transparency
Excluding side-effects, expressions can be replaced with its
evaluation with keeping the meaning of program.
It is called referentially transparent
Referential transparent functions are called pure functions.
Abstracting from functionsAbstracting from functions
RethinkRethink combinecombinefunctionfunction
We de ned combinefunction as a binary operation of Int.
It's amazingly useful for fold-like operation.
scala val combine = (left:Int, right:Int) = left + right
combine: (Int, Int) = Int = function2
foldLeftfoldLeft
Here is the foldLeftsignature of Seq[A].
This foldLefttakes two arguments - one is a default value,
and another is a binary operation of Int.
def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
It folds the sequence from left to right. Thus:
means
(((0 + 1) + 2) + 3)
Seq(1,2,3).foldLeft(0)((x: Int, y:Int) = x + y)
ApplyApply combinecombineintointo foldLeftfoldLeft
operation.operation.
combineworks for Seq[Int]Then how about
Seq[Option[Int]]?
scala Seq(1,2,3).foldLeft(0)(combine)
res0: Int = 6
combiningcombining Option[Int]Option[Int]scala val combineOptions = (left:Option[Int], right:Option[Int
(left , right) match{
case (None, None) = None
case (Some(l), None) = Some(l)
case (None, Some(r)) = Some(r)
case (Some(l), Some(r)) = Some(l + r)
}
combineOptions: (Option[Int], Option[Int]) = Option[Int] = fun
Okay then, how about Seq[Option[String]]?
scala Seq(Some(1),None,Some(3)).foldLeft(None)(combineOptions)
res0: Option[Int] = Some(4)
Do we have to de ne combineOptionXXXfor each Option[T]?
Abstract from functions.Abstract from functions.
We see the following operations are required for the element
type of Seqand its foldLeftoperation.
returning default value
binary operation
Let's abstract these two and make a certain type for them.
We call the type Monoid.
MonoidMonoid??
Monoidcan be de ned as follows.
trait Monoid[T] {
def empty: T
def combine(t1: T, t2: T): T
}
De neDe ne MonoidMonoidofof IntIntandand StringString
In this context, implicitis the keyword to pass a value as an
argument implicitly.
implicit val intMonoid: Monoid[Int] = new Monoid[Int] {
val empty: Int = 0
def combine(left: Int, right: Int): Int = left + right
}
implicit val stringMonoid: Monoid[String] = new Monoid[String] {
val empty: String = 
def combine(left: String, right: String): String = left + righ
}
Induce Monoid of Option[T]Induce Monoid of Option[T]
Now Monoid[Option[T]]instance can be induced from
Monoid[T]instance.
(Disclaimer: for simplicity, above induction function is de ned as T
type has to be Monoid, instead of Semigroup. )
implicit def optionMonoid[T](implicit M:Monoid[T]): Monoid[Optio
val empty: Option[T] = None
def combine(left:Option[T], right:Option[T]) =
(left , right) match{
case (None, None) = None
case (Some(l), None) = Some(l)
case (None, Some(r)) = Some(r)
case (Some(l), Some(r)) = Some(M.combine(l, r))
}
}
Compose Monoids for tupleCompose Monoids for tuple
You can also compose Monoid instances.
implicit def tupleMonoid[S,T](implicit MS:Monoid[S], MT:Monoid[T
new Monoid[(S,T)]{
val empty: (S,T) = (MS.empty, MT.empty)
def combine(left:(S,T), right:(S,T)) =
(MS.combine(left._1, right._1), MT.combine(left._2, righ
}
De neDe ne foldLeftfoldLeftmethod to usemethod to use
MonoidMonoiddef foldLeft[T](seq: Seq[T])(implicit M:Monoid[T]): T = seq.fold
//Monoid[Int]
scala foldLeft(Seq(1,2,3))
res0: Int = 6
//Monoid[Option[Int]]
scala foldLeft(Seq(Some(1), None, Some(3)))
res1: Option[Int] = Some(4)
//Monoid[Option[(Int,String)]]
scala foldLeft(Seq(Some((1,a)), None, Some(2,b)))
res2: Option[(Int,String)] = Some((3,ab))
Now you enjoy foldLeftfor any type with Monoid!
Cooler stu ofCooler stu of MonoidMonoid
Let's de ne a new fold operation like foldMapusing Monoid.
Now you can map values and fold them with traversing a
sequence just once!
def foldMap[T,U](s: Seq[T])(f: T = U)(implicit M:Monoid[U]) =
s.foldLeft(M.empty){case (l, r) = M.combine(l, f(r))}
scala foldMap(Seq(1,2,3))(_.toString)
res0: String = 123
RecapRecap MonoidMonoid- it's a typeclass.- it's a typeclass.
Monoid[T]is a type for a binary operation and a default value
against Ttype.
By de ning Monoid[T]instance against Ttype, new
behaviours are added into Ttype.
Monoidis so called typeclass and above description is the
bene t of typeclass.
What is typeclass?What is typeclass?
typeclass comes from Functional Language Haskell to
contrain a type parameter and admit new functions to its
type.
It means adding new behaviours into exisiting types without
changing their codebase!
Thus you can add new behaviours into even Stringtype
which souce codes cannot be modi ed or extended.
This is so called Adhoc Polymorphism.
Typeclasses out of the boxTypeclasses out of the box
Scala standard library de nes several typeclasses.
Ordering[T]typeclass is to de ne natural ordering of Ttype.
sortedmethod in Seq[T]use Ordering[T]typeclass
instances otherwise it fails to compile.
def sorted[B : A](implicit ord: math.Ordering[B]): List[A]
scala Seq(3,1,2).sorted
res3: Seq[Int] = List(1, 2, 3)
Typeclass works well with OOPTypeclass works well with OOP
Typeclass is not a concept just for Functional Programming.
Typeclass makes types more extesible without modi cation
of its original behaviour.
So typeclass is inline with open/closed principles.
Further readingFurther reading
Book:Book:
Functional Programming in Scala Chinese version
OSS projectOSS project
Both of these projects have a tons of typeclasses .
Scalaz
Cats: Typelevel.scala
Any question?Any question?

More Related Content

What's hot

Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
Philip Schwarz
 
Scala functions
Scala functionsScala functions
Scala functions
Knoldus Inc.
 
Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3
Scilab
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
Angelo Corsaro
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About Morphisms
Uberto Barbini
 
Functional Effects - Part 2
Functional Effects - Part 2Functional Effects - Part 2
Functional Effects - Part 2
Philip Schwarz
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Function Composition - forward composition versus backward composition
Function Composition - forward composition versus backward compositionFunction Composition - forward composition versus backward composition
Function Composition - forward composition versus backward composition
Philip Schwarz
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Java operators
Java operatorsJava operators
Java operators
Shehrevar Davierwala
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Lecture 4
Lecture 4Lecture 4
Lecture 4
Mohammed Saleh
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
Angelo Corsaro
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Operators In Java Part - 8
Operators In Java Part - 8Operators In Java Part - 8
Operators In Java Part - 8
MuhammadAtif231
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
Sheik Uduman Ali
 

What's hot (19)

Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
 
Scala functions
Scala functionsScala functions
Scala functions
 
Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3Scilab for real dummies j.heikell - part3
Scilab for real dummies j.heikell - part3
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
 
It's All About Morphisms
It's All About MorphismsIt's All About Morphisms
It's All About Morphisms
 
Functional Effects - Part 2
Functional Effects - Part 2Functional Effects - Part 2
Functional Effects - Part 2
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Function Composition - forward composition versus backward composition
Function Composition - forward composition versus backward compositionFunction Composition - forward composition versus backward composition
Function Composition - forward composition versus backward composition
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Java operators
Java operatorsJava operators
Java operators
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Operators In Java Part - 8
Operators In Java Part - 8Operators In Java Part - 8
Operators In Java Part - 8
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 

Similar to How to start functional programming (in Scala): Day1

Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
Francesco Bruni
 
Scala qq
Scala qqScala qq
Scala qq
羽祈 張
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Philip Schwarz
 
Please I want a detailed complete answers for each part.Then make.pdf
Please I want a detailed complete answers for each part.Then make.pdfPlease I want a detailed complete answers for each part.Then make.pdf
Please I want a detailed complete answers for each part.Then make.pdf
siennatimbok52331
 
Loops_in_Rv1.2b
Loops_in_Rv1.2bLoops_in_Rv1.2b
Loops_in_Rv1.2b
Carlo Fanara
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
Kurmendra Singh
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
amanabr
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp language
David Gu
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
jaba kumar
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
snowflakebatch
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
paijitk
 

Similar to How to start functional programming (in Scala): Day1 (20)

Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 
Scala qq
Scala qqScala qq
Scala qq
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
 
Please I want a detailed complete answers for each part.Then make.pdf
Please I want a detailed complete answers for each part.Then make.pdfPlease I want a detailed complete answers for each part.Then make.pdf
Please I want a detailed complete answers for each part.Then make.pdf
 
Loops_in_Rv1.2b
Loops_in_Rv1.2bLoops_in_Rv1.2b
Loops_in_Rv1.2b
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp language
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
 

More from Taisuke Oe

プレScalaMatsuri2019「スピーカー入門」
プレScalaMatsuri2019「スピーカー入門」プレScalaMatsuri2019「スピーカー入門」
プレScalaMatsuri2019「スピーカー入門」
Taisuke Oe
 
Monix Taskが便利だという話
Monix Taskが便利だという話Monix Taskが便利だという話
Monix Taskが便利だという話
Taisuke Oe
 
How to get along with implicits
How to get along with implicits How to get along with implicits
How to get along with implicits
Taisuke Oe
 
What Dotty fixes @ Scala関西サミット
What Dotty fixes @ Scala関西サミットWhat Dotty fixes @ Scala関西サミット
What Dotty fixes @ Scala関西サミット
Taisuke Oe
 
Real World Android Akka - 日本語版
Real World Android Akka - 日本語版Real World Android Akka - 日本語版
Real World Android Akka - 日本語版
Taisuke Oe
 
AuxパターンをDottyで解決する
AuxパターンをDottyで解決するAuxパターンをDottyで解決する
AuxパターンをDottyで解決する
Taisuke Oe
 
Real World Android Akka
Real World Android AkkaReal World Android Akka
Real World Android Akka
Taisuke Oe
 
Real world android akka
Real world android akkaReal world android akka
Real world android akka
Taisuke Oe
 
多相な関数の定義から学ぶ、型クラスデザインパターン
多相な関数の定義から学ぶ、型クラスデザインパターン多相な関数の定義から学ぶ、型クラスデザインパターン
多相な関数の定義から学ぶ、型クラスデザインパターン
Taisuke Oe
 
Android BLEのつらみを予防するTips
Android BLEのつらみを予防するTipsAndroid BLEのつらみを予防するTips
Android BLEのつらみを予防するTips
Taisuke Oe
 
BONXを支える技術:Bluetooth編 ~Bluetoothを120%使い倒す方法~
BONXを支える技術:Bluetooth編 ~Bluetoothを120%使い倒す方法~BONXを支える技術:Bluetooth編 ~Bluetoothを120%使い倒す方法~
BONXを支える技術:Bluetooth編 ~Bluetoothを120%使い倒す方法~
Taisuke Oe
 

More from Taisuke Oe (11)

プレScalaMatsuri2019「スピーカー入門」
プレScalaMatsuri2019「スピーカー入門」プレScalaMatsuri2019「スピーカー入門」
プレScalaMatsuri2019「スピーカー入門」
 
Monix Taskが便利だという話
Monix Taskが便利だという話Monix Taskが便利だという話
Monix Taskが便利だという話
 
How to get along with implicits
How to get along with implicits How to get along with implicits
How to get along with implicits
 
What Dotty fixes @ Scala関西サミット
What Dotty fixes @ Scala関西サミットWhat Dotty fixes @ Scala関西サミット
What Dotty fixes @ Scala関西サミット
 
Real World Android Akka - 日本語版
Real World Android Akka - 日本語版Real World Android Akka - 日本語版
Real World Android Akka - 日本語版
 
AuxパターンをDottyで解決する
AuxパターンをDottyで解決するAuxパターンをDottyで解決する
AuxパターンをDottyで解決する
 
Real World Android Akka
Real World Android AkkaReal World Android Akka
Real World Android Akka
 
Real world android akka
Real world android akkaReal world android akka
Real world android akka
 
多相な関数の定義から学ぶ、型クラスデザインパターン
多相な関数の定義から学ぶ、型クラスデザインパターン多相な関数の定義から学ぶ、型クラスデザインパターン
多相な関数の定義から学ぶ、型クラスデザインパターン
 
Android BLEのつらみを予防するTips
Android BLEのつらみを予防するTipsAndroid BLEのつらみを予防するTips
Android BLEのつらみを予防するTips
 
BONXを支える技術:Bluetooth編 ~Bluetoothを120%使い倒す方法~
BONXを支える技術:Bluetooth編 ~Bluetoothを120%使い倒す方法~BONXを支える技術:Bluetooth編 ~Bluetoothを120%使い倒す方法~
BONXを支える技術:Bluetooth編 ~Bluetoothを120%使い倒す方法~
 

Recently uploaded

03. Ruby Variables & Regex - Ruby Core Teaching
03. Ruby Variables & Regex - Ruby Core Teaching03. Ruby Variables & Regex - Ruby Core Teaching
03. Ruby Variables & Regex - Ruby Core Teaching
quanhoangd129
 
Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)
andrehoraa
 
08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching
quanhoangd129
 
02. Ruby Basic slides - Ruby Core Teaching
02. Ruby Basic slides - Ruby Core Teaching02. Ruby Basic slides - Ruby Core Teaching
02. Ruby Basic slides - Ruby Core Teaching
quanhoangd129
 
Applitools Autonomous 2.0 Sneak Peek.pdf
Applitools Autonomous 2.0 Sneak Peek.pdfApplitools Autonomous 2.0 Sneak Peek.pdf
Applitools Autonomous 2.0 Sneak Peek.pdf
Applitools
 
07. Ruby String Slides - Ruby Core Teaching
07. Ruby String Slides - Ruby Core Teaching07. Ruby String Slides - Ruby Core Teaching
07. Ruby String Slides - Ruby Core Teaching
quanhoangd129
 
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
norina2645
 
UMiami degree offer diploma Transcript
UMiami degree offer diploma TranscriptUMiami degree offer diploma Transcript
UMiami degree offer diploma Transcript
attueb
 
06. Ruby Array & Hash - Ruby Core Teaching
06. Ruby Array & Hash - Ruby Core Teaching06. Ruby Array & Hash - Ruby Core Teaching
06. Ruby Array & Hash - Ruby Core Teaching
quanhoangd129
 
DSD-INT 2024 Rainfall nowcasting – now and then - Uijlenhoet
DSD-INT 2024 Rainfall nowcasting – now and then - UijlenhoetDSD-INT 2024 Rainfall nowcasting – now and then - Uijlenhoet
DSD-INT 2024 Rainfall nowcasting – now and then - Uijlenhoet
Deltares
 
05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching
quanhoangd129
 
09. Ruby Object Oriented Programming - Ruby Core Teaching
09. Ruby Object Oriented Programming - Ruby Core Teaching09. Ruby Object Oriented Programming - Ruby Core Teaching
09. Ruby Object Oriented Programming - Ruby Core Teaching
quanhoangd129
 
Amadeus Travel API, Amadeus Booking API, Amadeus GDS
Amadeus Travel API, Amadeus Booking API, Amadeus GDSAmadeus Travel API, Amadeus Booking API, Amadeus GDS
Amadeus Travel API, Amadeus Booking API, Amadeus GDS
aadhiyaeliza
 
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
John Gallagher
 
BATber53 AWS Modernize your applications with purpose-built AWS databases
BATber53 AWS Modernize your applications with purpose-built AWS databasesBATber53 AWS Modernize your applications with purpose-built AWS databases
BATber53 AWS Modernize your applications with purpose-built AWS databases
BATbern
 
B.Sc. Computer Science Department PPT 2024
B.Sc. Computer Science Department PPT 2024B.Sc. Computer Science Department PPT 2024
B.Sc. Computer Science Department PPT 2024
vmsdeptcom
 
How To Fill Timesheet in TaskSprint: Quick Guide 2024
How To Fill Timesheet in TaskSprint: Quick Guide 2024How To Fill Timesheet in TaskSprint: Quick Guide 2024
How To Fill Timesheet in TaskSprint: Quick Guide 2024
TaskSprint | Employee Efficiency Software
 
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
rachitkumar09887
 
Russian Girls Call Mumbai 🛵🚡9833363713 💃 Choose Best And Top Girl Service And...
Russian Girls Call Mumbai 🛵🚡9833363713 💃 Choose Best And Top Girl Service And...Russian Girls Call Mumbai 🛵🚡9833363713 💃 Choose Best And Top Girl Service And...
Russian Girls Call Mumbai 🛵🚡9833363713 💃 Choose Best And Top Girl Service And...
dream girl
 
ERP Software Solutions Provider in Coimbatore
ERP Software Solutions Provider in CoimbatoreERP Software Solutions Provider in Coimbatore
ERP Software Solutions Provider in Coimbatore
Nextskill Technologies
 

Recently uploaded (20)

03. Ruby Variables & Regex - Ruby Core Teaching
03. Ruby Variables & Regex - Ruby Core Teaching03. Ruby Variables & Regex - Ruby Core Teaching
03. Ruby Variables & Regex - Ruby Core Teaching
 
Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)Predicting Test Results without Execution (FSE 2024)
Predicting Test Results without Execution (FSE 2024)
 
08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching08. Ruby Enumerable - Ruby Core Teaching
08. Ruby Enumerable - Ruby Core Teaching
 
02. Ruby Basic slides - Ruby Core Teaching
02. Ruby Basic slides - Ruby Core Teaching02. Ruby Basic slides - Ruby Core Teaching
02. Ruby Basic slides - Ruby Core Teaching
 
Applitools Autonomous 2.0 Sneak Peek.pdf
Applitools Autonomous 2.0 Sneak Peek.pdfApplitools Autonomous 2.0 Sneak Peek.pdf
Applitools Autonomous 2.0 Sneak Peek.pdf
 
07. Ruby String Slides - Ruby Core Teaching
07. Ruby String Slides - Ruby Core Teaching07. Ruby String Slides - Ruby Core Teaching
07. Ruby String Slides - Ruby Core Teaching
 
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
Celebrity Girls Call Mumbai 🛵🚡9910780858 💃 Choose Best And Top Girl Service A...
 
UMiami degree offer diploma Transcript
UMiami degree offer diploma TranscriptUMiami degree offer diploma Transcript
UMiami degree offer diploma Transcript
 
06. Ruby Array & Hash - Ruby Core Teaching
06. Ruby Array & Hash - Ruby Core Teaching06. Ruby Array & Hash - Ruby Core Teaching
06. Ruby Array & Hash - Ruby Core Teaching
 
DSD-INT 2024 Rainfall nowcasting – now and then - Uijlenhoet
DSD-INT 2024 Rainfall nowcasting – now and then - UijlenhoetDSD-INT 2024 Rainfall nowcasting – now and then - Uijlenhoet
DSD-INT 2024 Rainfall nowcasting – now and then - Uijlenhoet
 
05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching
 
09. Ruby Object Oriented Programming - Ruby Core Teaching
09. Ruby Object Oriented Programming - Ruby Core Teaching09. Ruby Object Oriented Programming - Ruby Core Teaching
09. Ruby Object Oriented Programming - Ruby Core Teaching
 
Amadeus Travel API, Amadeus Booking API, Amadeus GDS
Amadeus Travel API, Amadeus Booking API, Amadeus GDSAmadeus Travel API, Amadeus Booking API, Amadeus GDS
Amadeus Travel API, Amadeus Booking API, Amadeus GDS
 
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
Fix Production Bugs Quickly - The Power of Structured Logging in Ruby on Rail...
 
BATber53 AWS Modernize your applications with purpose-built AWS databases
BATber53 AWS Modernize your applications with purpose-built AWS databasesBATber53 AWS Modernize your applications with purpose-built AWS databases
BATber53 AWS Modernize your applications with purpose-built AWS databases
 
B.Sc. Computer Science Department PPT 2024
B.Sc. Computer Science Department PPT 2024B.Sc. Computer Science Department PPT 2024
B.Sc. Computer Science Department PPT 2024
 
How To Fill Timesheet in TaskSprint: Quick Guide 2024
How To Fill Timesheet in TaskSprint: Quick Guide 2024How To Fill Timesheet in TaskSprint: Quick Guide 2024
How To Fill Timesheet in TaskSprint: Quick Guide 2024
 
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
Agra Girls Call Agra 0X0000000X Unlimited Short Providing Girls Service Avail...
 
Russian Girls Call Mumbai 🛵🚡9833363713 💃 Choose Best And Top Girl Service And...
Russian Girls Call Mumbai 🛵🚡9833363713 💃 Choose Best And Top Girl Service And...Russian Girls Call Mumbai 🛵🚡9833363713 💃 Choose Best And Top Girl Service And...
Russian Girls Call Mumbai 🛵🚡9833363713 💃 Choose Best And Top Girl Service And...
 
ERP Software Solutions Provider in Coimbatore
ERP Software Solutions Provider in CoimbatoreERP Software Solutions Provider in Coimbatore
ERP Software Solutions Provider in Coimbatore
 

How to start functional programming (in Scala): Day1

  • 1. How to startHow to start Functional ProgrammingFunctional Programming (in Scala):Day1(in Scala):Day1
  • 2. Who am I?Who am I?
  • 3. Taisuke Oe (Twitter: @OE_uia, GitHub: @taisukeoe) ScalaMatsuri organizer as a chairperson Technical Advisor at Septeni Original, Inc.
  • 4. ScalaMatsuri CFP is open now!ScalaMatsuri CFP is open now!
  • 6. Functional Programming is the paradigm to construct a software with composing computations like functions. (in a casual de nition)
  • 7. Through learning FP, you can learn the ways to make functions or comutations smallish, composable and iducible.
  • 8. That helps to keep your software clean and extensible, even in OOP.
  • 9. Scala is indeed a functional language,Scala is indeed a functional language, butbut not very strict about FP principles.
  • 10. Scala uni es FP and OOP, and recommends to leverage both of their strengths.
  • 11. Today's topicToday's topic Function compositions. Function purity. Abstracting from functions and composition.
  • 12. Composing functions andComposing functions and methods.methods.
  • 13. What is a function?What is a function? A function is a computation to transform inputs into outputs. It's an instance of FunctionNtraits in Scala. FunctionNmeans a function type which takes N arguments (from 0 to 22). Function0[T], Function1[T1,T2], ... , Function22[T1,...,T23] Function1Function1 Int=Intis a type alias to Function1[Int,Int]. scala val double = (i:Int) = i * 2 double: Int = Int = function1
  • 14. Function1 is composable.Function1 is composable. Function1has andThenand composemethod for function compositions. scala val quadraple = double compose double quadraple: Int = Int = function1 scala quadraple(3) res0: Int = 12
  • 15. Function2 to 22 don't have thoseFunction2 to 22 don't have those methods, but...methods, but...
  • 16. Function2 to 22 can be curried.Function2 to 22 can be curried. Curryingmeans converting a multiple argument funtion to Function1.
  • 17. Currying Function2Currying Function2 Function2[Int,String,Int]is curriedto Function1[Int,Function1[String,Int]] scala val combine = (left:Int, right:Int) = left + right combine: (Int, Int) = Int = function2 scala combine.curried res0: Int = (Int = Int) = function1
  • 18. Function2 to 22 can be composed viaFunction2 to 22 can be composed via currying.currying. Thus Function1- Function22are composable. scala double andThen combine.curried res0: Int = (Int = Int) = function1
  • 19. FP fundamentalsFP fundamentals As we see, functions can take another function as an agrument or a return value. This is to say a function is a rst class citizen. Those functions are called higher order functions. Above two are fundamentals in FP.
  • 20. Methods and type parameterMethods and type parameter
  • 21. Di erence from functionsDi erence from functions Method is de ned by def keyword. Methods can be expanded to FunctionNby _. (eta-expansion) scala def double(i:Int):Int = i * 2 double: (i: Int)Int scala double _ res0: Int = Int = function1
  • 22. Methods can take type parameters or an implicit parameter list, while functions cannot.
  • 23. Methods with type parameterMethods with type parameter Seq[T] has a method map[U]which modi es Ttyped elements into Utyped elements. def map[U](f: T = U): Seq[U] scala Seq(1,2,3).map(_ + 1) res0: Seq[Int] = List(2,3,4)
  • 24. Combine all together.Combine all together. Now we know function composition basics! scala val apCurried = combine.curried apCurried: Int = (Int = Int) = function1 // (X + 3) * 2 scala val plus3Double = apCurried(3) andThen double plus3Double: Int = Int = function1 scala seq = Seq(1,2,3).map(plus3Double) seq: Seq[Int] = Seq(8,10,12)
  • 25. Pure FunctionsPure Functions All functions so far are pure functions They always return the same value with the same arguments.
  • 26. Watch out side e ectsWatch out side e ects Changing any state. Depending on mutable state which may change. Standard ouput File I/O Throwing exceptions. All above side effects may change functions behaviour depends on state.
  • 27. What isWhat is resultresult?? var counter = 0 val next = (nth: Int) = { counter += nth counter } scala next(1) res0: Int = 1 scala val result = (next andThen next andThen next)(3)
  • 28. You have to care the order of execution and each state, even if you compose! It's sometimes hard to predict how impure functions behave. scala val result = (next andThen next andThen next)(3) result: Int = 16
  • 29. localize side-e ectslocalize side-e ects All side effects cannot be removed from your program. The key is to localize and seperate side effects from other functions.
  • 30. Referential transparencyReferential transparency Excluding side-effects, expressions can be replaced with its evaluation with keeping the meaning of program. It is called referentially transparent Referential transparent functions are called pure functions.
  • 32. RethinkRethink combinecombinefunctionfunction We de ned combinefunction as a binary operation of Int. It's amazingly useful for fold-like operation. scala val combine = (left:Int, right:Int) = left + right combine: (Int, Int) = Int = function2
  • 33. foldLeftfoldLeft Here is the foldLeftsignature of Seq[A]. This foldLefttakes two arguments - one is a default value, and another is a binary operation of Int. def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
  • 34. It folds the sequence from left to right. Thus: means (((0 + 1) + 2) + 3) Seq(1,2,3).foldLeft(0)((x: Int, y:Int) = x + y)
  • 35. ApplyApply combinecombineintointo foldLeftfoldLeft operation.operation. combineworks for Seq[Int]Then how about Seq[Option[Int]]? scala Seq(1,2,3).foldLeft(0)(combine) res0: Int = 6
  • 36. combiningcombining Option[Int]Option[Int]scala val combineOptions = (left:Option[Int], right:Option[Int (left , right) match{ case (None, None) = None case (Some(l), None) = Some(l) case (None, Some(r)) = Some(r) case (Some(l), Some(r)) = Some(l + r) } combineOptions: (Option[Int], Option[Int]) = Option[Int] = fun
  • 37. Okay then, how about Seq[Option[String]]? scala Seq(Some(1),None,Some(3)).foldLeft(None)(combineOptions) res0: Option[Int] = Some(4)
  • 38. Do we have to de ne combineOptionXXXfor each Option[T]?
  • 39. Abstract from functions.Abstract from functions. We see the following operations are required for the element type of Seqand its foldLeftoperation. returning default value binary operation
  • 40. Let's abstract these two and make a certain type for them. We call the type Monoid.
  • 41. MonoidMonoid?? Monoidcan be de ned as follows. trait Monoid[T] { def empty: T def combine(t1: T, t2: T): T }
  • 42. De neDe ne MonoidMonoidofof IntIntandand StringString In this context, implicitis the keyword to pass a value as an argument implicitly. implicit val intMonoid: Monoid[Int] = new Monoid[Int] { val empty: Int = 0 def combine(left: Int, right: Int): Int = left + right }
  • 43. implicit val stringMonoid: Monoid[String] = new Monoid[String] { val empty: String = def combine(left: String, right: String): String = left + righ }
  • 44. Induce Monoid of Option[T]Induce Monoid of Option[T] Now Monoid[Option[T]]instance can be induced from Monoid[T]instance.
  • 45. (Disclaimer: for simplicity, above induction function is de ned as T type has to be Monoid, instead of Semigroup. ) implicit def optionMonoid[T](implicit M:Monoid[T]): Monoid[Optio val empty: Option[T] = None def combine(left:Option[T], right:Option[T]) = (left , right) match{ case (None, None) = None case (Some(l), None) = Some(l) case (None, Some(r)) = Some(r) case (Some(l), Some(r)) = Some(M.combine(l, r)) } }
  • 46. Compose Monoids for tupleCompose Monoids for tuple You can also compose Monoid instances. implicit def tupleMonoid[S,T](implicit MS:Monoid[S], MT:Monoid[T new Monoid[(S,T)]{ val empty: (S,T) = (MS.empty, MT.empty) def combine(left:(S,T), right:(S,T)) = (MS.combine(left._1, right._1), MT.combine(left._2, righ }
  • 47. De neDe ne foldLeftfoldLeftmethod to usemethod to use MonoidMonoiddef foldLeft[T](seq: Seq[T])(implicit M:Monoid[T]): T = seq.fold
  • 48. //Monoid[Int] scala foldLeft(Seq(1,2,3)) res0: Int = 6 //Monoid[Option[Int]] scala foldLeft(Seq(Some(1), None, Some(3))) res1: Option[Int] = Some(4) //Monoid[Option[(Int,String)]] scala foldLeft(Seq(Some((1,a)), None, Some(2,b))) res2: Option[(Int,String)] = Some((3,ab))
  • 49. Now you enjoy foldLeftfor any type with Monoid!
  • 50. Cooler stu ofCooler stu of MonoidMonoid Let's de ne a new fold operation like foldMapusing Monoid.
  • 51. Now you can map values and fold them with traversing a sequence just once! def foldMap[T,U](s: Seq[T])(f: T = U)(implicit M:Monoid[U]) = s.foldLeft(M.empty){case (l, r) = M.combine(l, f(r))} scala foldMap(Seq(1,2,3))(_.toString) res0: String = 123
  • 52. RecapRecap MonoidMonoid- it's a typeclass.- it's a typeclass. Monoid[T]is a type for a binary operation and a default value against Ttype.
  • 53. By de ning Monoid[T]instance against Ttype, new behaviours are added into Ttype.
  • 54. Monoidis so called typeclass and above description is the bene t of typeclass.
  • 55. What is typeclass?What is typeclass? typeclass comes from Functional Language Haskell to contrain a type parameter and admit new functions to its type.
  • 56. It means adding new behaviours into exisiting types without changing their codebase!
  • 57. Thus you can add new behaviours into even Stringtype which souce codes cannot be modi ed or extended.
  • 58. This is so called Adhoc Polymorphism.
  • 59. Typeclasses out of the boxTypeclasses out of the box Scala standard library de nes several typeclasses. Ordering[T]typeclass is to de ne natural ordering of Ttype.
  • 60. sortedmethod in Seq[T]use Ordering[T]typeclass instances otherwise it fails to compile. def sorted[B : A](implicit ord: math.Ordering[B]): List[A] scala Seq(3,1,2).sorted res3: Seq[Int] = List(1, 2, 3)
  • 61. Typeclass works well with OOPTypeclass works well with OOP Typeclass is not a concept just for Functional Programming.
  • 62. Typeclass makes types more extesible without modi cation of its original behaviour.
  • 63. So typeclass is inline with open/closed principles.
  • 64. Further readingFurther reading Book:Book: Functional Programming in Scala Chinese version
  • 65. OSS projectOSS project Both of these projects have a tons of typeclasses . Scalaz Cats: Typelevel.scala