SlideShare a Scribd company logo
1 of 98
Download to read offline
Functional
Programming 101 with
Scala and ZIO
Functional World
April 15th, 2021
Jorge Vásquez
Scala Developer
@Scalac
Agenda
Agenda
• Functional Programming (FP)
basic concepts
Agenda
• Functional Programming (FP)
basic concepts
• ZIO basic concepts
Agenda
• Functional Programming (FP)
basic concepts
• ZIO basic concepts
• Live coding: Tic-Tac-Toe game
What is Functional
Programming?
What is Functional Programming?
Programming paradigm, where programs are a
composition of pure functions
Characteristics of a
Pure Function
Characteristics of a
Pure Function
• Total
Characteristics of a
Pure Function
• Total
• Deterministic and depends on its
inputs only
Characteristics of a
Pure Function
• Total
• Deterministic and depends on its
inputs only
• Must not have side effects
A Pure Function must be Total
For each input that is provided to the function there must
be a defined output
A Pure Function must be Total
def divide(a: Int, b: Int): Int = a / b
divide(5, 0)
// java.lang.ArithmeticException: / by zero
A Pure Function must be Total
def divide(a: Int, b: Int): Int = a / b
divide(5, 0)
// java.lang.ArithmeticException: / by zero
A Pure Function must be Total
def divide(a: Int, b: Int): Int = a / b
divide(5, 0)
// java.lang.ArithmeticException: / by zero
A Pure Function must be Total
def divide(a: Int, b: Int): Int = a / b
divide(5, 0)
// java.lang.ArithmeticException: / by zero
A Pure Function must be Total
def divide(a: Int, b: Int): Int = a / b
A Pure Function must be Total
def divide(a: Int, b: Int): Int = a / b
• The signature of this function tells a lie!
A Pure Function must be Total
def divide(a: Int, b: Int): Int = a / b
• The signature of this function tells a lie!
• Every time we call it we will have to be very careful
A Pure Function must be Total
def divide(a: Int, b: Int): Int = a / b
• The signature of this function tells a lie!
• Every time we call it we will have to be very careful
• Runtime exceptions can happen. The compiler is not
able to do anything to help us to avoid this
A Pure Function must be Total
def divide(a: Int, b: Int): Option[Int] =
if (b != 0) Some(a / b) else None
divide(5, 0)
// None
A Pure Function must be Total
def divide(a: Int, b: Int): Option[Int] =
if (b != 0) Some(a / b) else None
divide(5, 0)
// None
A Pure Function must be Total
def divide(a: Int, b: Int): Option[Int] =
if (b != 0) Some(a / b) else None
divide(5, 0)
// None
A Pure Function must be Total
def divide(a: Int, b: Int): Option[Int] =
if (b != 0) Some(a / b) else None
divide(5, 0)
// None
A Pure Function must be Total
def divide(a: Int, b: Int): Option[Int] =
if (b != 0) Some(a / b) else None
A Pure Function must be Total
def divide(a: Int, b: Int): Option[Int] =
if (b != 0) Some(a / b) else None
• The function’s signature clearly communicates that some
inputs are not handled
A Pure Function must be Total
def divide(a: Int, b: Int): Option[Int] =
if (b != 0) Some(a / b) else None
• The function’s signature clearly communicates that some
inputs are not handled
• The compiler will force us to consider the case in which the
result is not defined
A Pure Function must be Total
def divide(a: Int, b: Int): Option[Int] =
if (b != 0) Some(a / b) else None
• The function’s signature clearly communicates that some
inputs are not handled
• The compiler will force us to consider the case in which the
result is not defined
• No runtime exceptions!
A Pure Function must be Deterministic
and depend only on its inputs
For each input that is provided to the function, the same
output must be returned, no matter how many times the
function is called
A Pure Function must be Deterministic
and depend only on its inputs
def generateRandomInt(): Int = (new scala.util.Random).nextInt
generateRandomInt() // Result: -272770531
generateRandomInt() // Result: 217937820
A Pure Function must be Deterministic
and depend only on its inputs
def generateRandomInt(): Int = (new scala.util.Random).nextInt
generateRandomInt() // Result: -272770531
generateRandomInt() // Result: 217937820
A Pure Function must be Deterministic
and depend only on its inputs
def generateRandomInt(): Int = (new scala.util.Random).nextInt
generateRandomInt() // Result: -272770531
generateRandomInt() // Result: 217937820
A Pure Function must be Deterministic
and depend only on its inputs
def generateRandomInt(): Int = (new scala.util.Random).nextInt
generateRandomInt() // Result: -272770531
generateRandomInt() // Result: 217937820
A Pure Function must be Deterministic
and depend only on its inputs
def generateRandomInt(): Int = (new scala.util.Random).nextInt
A Pure Function must be Deterministic
and depend only on its inputs
def generateRandomInt(): Int = (new scala.util.Random).nextInt
• Clearly not deterministic!
A Pure Function must be Deterministic
and depend only on its inputs
def generateRandomInt(): Int = (new scala.util.Random).nextInt
• Clearly not deterministic!
• The signature is misleading, because there is a hidden
dependency on a scala.util.Random object
A Pure Function must be Deterministic
and depend only on its inputs
def generateRandomInt(): Int = (new scala.util.Random).nextInt
• Clearly not deterministic!
• The signature is misleading, because there is a hidden
dependency on a scala.util.Random object
• Difficult to test because we can never really be sure how the
function will behave
A Pure Function must be Deterministic
and depend only on its inputs
final case class RNG(seed: Long) {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL
val nextRNG = RNG(newSeed)
val n = (newSeed >>> 16).toInt
(n, nextRNG)
}
}
def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt
val random = RNG(10)
val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181)
val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181)
val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
A Pure Function must be Deterministic
and depend only on its inputs
final case class RNG(seed: Long) {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL
val nextRNG = RNG(newSeed)
val n = (newSeed >>> 16).toInt
(n, nextRNG)
}
}
def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt
val random = RNG(10)
val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181)
val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181)
val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
A Pure Function must be Deterministic
and depend only on its inputs
final case class RNG(seed: Long) {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL
val nextRNG = RNG(newSeed)
val n = (newSeed >>> 16).toInt
(n, nextRNG)
}
}
def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt
val random = RNG(10)
val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181)
val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181)
val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
A Pure Function must be Deterministic
and depend only on its inputs
final case class RNG(seed: Long) {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL
val nextRNG = RNG(newSeed)
val n = (newSeed >>> 16).toInt
(n, nextRNG)
}
}
def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt
val random = RNG(10)
val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181)
val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181)
val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
A Pure Function must be Deterministic
and depend only on its inputs
final case class RNG(seed: Long) {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL
val nextRNG = RNG(newSeed)
val n = (newSeed >>> 16).toInt
(n, nextRNG)
}
}
def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt
val random = RNG(10)
val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181)
val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181)
val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
A Pure Function must be Deterministic
and depend only on its inputs
final case class RNG(seed: Long) {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL
val nextRNG = RNG(newSeed)
val n = (newSeed >>> 16).toInt
(n, nextRNG)
}
}
def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt
val random = RNG(10)
val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181)
val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181)
val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
A Pure Function must not have side
effects
Finally, a function must not have any side effects:
A Pure Function must not have side
effects
Finally, a function must not have any side effects:
• Memory mutations
A Pure Function must not have side
effects
Finally, a function must not have any side effects:
• Memory mutations
• Interactions with the outside world, such as:
A Pure Function must not have side
effects
Finally, a function must not have any side effects:
• Memory mutations
• Interactions with the outside world, such as:
• Printing messages to the console
A Pure Function must not have side
effects
Finally, a function must not have any side effects:
• Memory mutations
• Interactions with the outside world, such as:
• Printing messages to the console
• Calling an external API
A Pure Function must not have side
effects
Finally, a function must not have any side effects:
• Memory mutations
• Interactions with the outside world, such as:
• Printing messages to the console
• Calling an external API
• Querying a database
A Pure Function must not have side
effects
A pure function can only:
A Pure Function must not have side
effects
A pure function can only:
• Work with immutable values
A Pure Function must not have side
effects
A pure function can only:
• Work with immutable values
• Return an output for a corresponding input
A Pure Function must not have side
effects
var a = 0
def increment(inc: Int): Int = {
a + = inc
a
}
A Pure Function must not have side
effects
def add(a: Int, b: Int): Int = {
println(s "Adding two integers: $a and $b")
a + b
}
FP vs. OOP
FP vs. OOP
• Variables: Immutable / Mutable
FP vs. OOP
• Variables: Immutable / Mutable
• Side effects: NO / YES
FP vs. OOP
• Variables: Immutable / Mutable
• Side effects: NO / YES
• Iterations: Recursion / Loops
FP vs. OOP
FP vs. OOP
• State: Flows through pure
functions / Shared by several
objects
FP vs. OOP
• State: Flows through pure
functions / Shared by several
objects
• Key elements: Immutable values
and Functions / Objects and
Methods
FP vs. OOP
• State: Flows through pure
functions / Shared by several
objects
• Key elements: Immutable values
and Functions / Objects and
Methods
• Suitable for Parallel
programming: YES / Not so
much
Benefits of
Functional
Programming
Benefits of
Functional
Programming
• Local reasoning
Benefits of
Functional
Programming
• Local reasoning
• Referential transparency ->
Fearless refactoring!
Benefits of
Functional
Programming
• Local reasoning
• Referential transparency ->
Fearless refactoring!
• Conciseness -> Fewer bugs!
Benefits of
Functional
Programming
Benefits of
Functional
Programming
• Easier to test
Benefits of
Functional
Programming
• Easier to test
• Applications behave more
predictably
Benefits of
Functional
Programming
• Easier to test
• Applications behave more
predictably
• Allows us to write correct parallel
programs
Functional Effects
Functional Effects
• Descriptions of interactions with
the outside world
Functional Effects
• Descriptions of interactions with
the outside world
• Immutable values that can serve
as inputs and outputs of pure
functions
Functional Effects
• Descriptions of interactions with
the outside world
• Immutable values that can serve
as inputs and outputs of pure
functions
• They are executed only at the
End of the World
Enter ZIO!
ZIO - The Library
Allows us to build modern applications, using the
principles of Functional Programming!
ZIO - The Library
ZIO - The Library
• Asynchronous & Concurrent -> Fiber-based model!
ZIO - The Library
• Asynchronous & Concurrent -> Fiber-based model!
• Resilient -> Leverages the power of Scala's Type System!
ZIO - The Library
• Asynchronous & Concurrent -> Fiber-based model!
• Resilient -> Leverages the power of Scala's Type System!
• Efficient -> Apps that never leak resources!
ZIO - The Library
• Asynchronous & Concurrent -> Fiber-based model!
• Resilient -> Leverages the power of Scala's Type System!
• Efficient -> Apps that never leak resources!
• Easy to understand and test -> Thanks to superior
composability!
ZIO - The Data Type
ZIO[-R, +E, +A]
ZIO - The Data Type
ZIO[-R, +E, +A]
• Core type of the ZIO Library
ZIO - The Data Type
ZIO[-R, +E, +A]
• Core type of the ZIO Library
• Functional Effect
ZIO - The Data Type
A good mental model is the following:
R => Either[E, A]
This means that a ZIO effect:
ZIO - The Data Type
A good mental model is the following:
R => Either[E, A]
This means that a ZIO effect:
• Needs an environment of type R to run
ZIO - The Data Type
A good mental model is the following:
R => Either[E, A]
This means that a ZIO effect:
• Needs an environment of type R to run
• It may fail with an error of type E
ZIO - The Data Type
A good mental model is the following:
R => Either[E, A]
This means that a ZIO effect:
• Needs an environment of type R to run
• It may fail with an error of type E
• Or it may complete successfully, returning a value of type A
ZIO - The Data Type
Common aliases:
Task[+A] = ZIO[Any, Throwable, +A]
UIO[+A] = ZIO[Any, Nothing, +A]
RIO[-R, +A] = ZIO[-R, Throwable, +A]
IO[+E, +A] = ZIO[Any, E, A]
URIO[-R, +A] = ZIO[R, Nothing, A]
Live coding
Tic-Tac-Toe game with ZIO!
https://github.com/jorge-vasquez-2301/zio-tictactoe
Where to learn more
• Introduction to Programming with ZIO Functional Effects - Scalac Blog
• Introducción a la Programación con Efectos Funcionales usando ZIO -
Scalac Blog
• Mastering modularity in ZIO with ZLayer - Scalac Blog
• How to write a (completely lock-free) concurrent LRU Cache with ZIO STM
• ZIO Official Site
• Zionomicon
Where to learn more
Learn how to use the full potential of Functional
Programming with Scalac Trainings!
• Scala 2 for Java Developers
• Scala 3 for Scala 2 Developers
• ZIO
We are hiring!
https://scalac.io/careers/
@majakryzan
maja.kryzan@scalac.io
Contact me
@jorvasquez2301
jorge-vasquez-2301
jorge.vasquez@scalac.io

More Related Content

What's hot

Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside💡 Tomasz Kogut
 
How to successfully manage a ZIO fiber’s lifecycle - Functional Scala 2021
How to successfully manage a ZIO fiber’s lifecycle - Functional Scala 2021How to successfully manage a ZIO fiber’s lifecycle - Functional Scala 2021
How to successfully manage a ZIO fiber’s lifecycle - Functional Scala 2021Natan Silnitsky
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Philip Schwarz
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...Philip Schwarz
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldPhilip Schwarz
 
Quill vs Slick Smackdown
Quill vs Slick SmackdownQuill vs Slick Smackdown
Quill vs Slick SmackdownAlexander Ioffe
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't FreeKelley Robinson
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsJorge Vásquez
 
Boost your productivity with Scala tooling!
Boost your productivity  with Scala tooling!Boost your productivity  with Scala tooling!
Boost your productivity with Scala tooling!MeriamLachkar1
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional WorldDebasish Ghosh
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018John De Goes
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them AllJohn De Goes
 

What's hot (20)

ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Taking your side effects aside
Taking your side effects asideTaking your side effects aside
Taking your side effects aside
 
How to successfully manage a ZIO fiber’s lifecycle - Functional Scala 2021
How to successfully manage a ZIO fiber’s lifecycle - Functional Scala 2021How to successfully manage a ZIO fiber’s lifecycle - Functional Scala 2021
How to successfully manage a ZIO fiber’s lifecycle - Functional Scala 2021
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
 
Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...
 
The Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and FoldThe Functional Programming Triad of Map, Filter and Fold
The Functional Programming Triad of Map, Filter and Fold
 
Quill vs Slick Smackdown
Quill vs Slick SmackdownQuill vs Slick Smackdown
Quill vs Slick Smackdown
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
 
Introduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effectsIntroduction to programming with ZIO functional effects
Introduction to programming with ZIO functional effects
 
Boost your productivity with Scala tooling!
Boost your productivity  with Scala tooling!Boost your productivity  with Scala tooling!
Boost your productivity with Scala tooling!
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional World
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018Blazing Fast, Pure Effects without Monads — LambdaConf 2018
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 

Similar to Functional Programming 101 with Scala and ZIO

Abstracting Vector Architectures in Library Generators: Case Study Convolutio...
Abstracting Vector Architectures in Library Generators: Case Study Convolutio...Abstracting Vector Architectures in Library Generators: Case Study Convolutio...
Abstracting Vector Architectures in Library Generators: Case Study Convolutio...ETH Zurich
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...Positive Hack Days
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...Linaro
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?Federico Tomassetti
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kros Huang
 
Reverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading SkillsReverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading SkillsAsuka Nakajima
 
Fourier project presentation
Fourier project  presentationFourier project  presentation
Fourier project presentation志璿 楊
 
Scaladays 2011 - The Ease of Scalaz
Scaladays 2011 - The Ease of ScalazScaladays 2011 - The Ease of Scalaz
Scaladays 2011 - The Ease of ScalazHeiko Seeberger
 
Arduino for Beginners
Arduino for BeginnersArduino for Beginners
Arduino for BeginnersSarwan Singh
 
Java PSkills Session-3 PNR.pptx
Java PSkills Session-3 PNR.pptxJava PSkills Session-3 PNR.pptx
Java PSkills Session-3 PNR.pptxssuser99ca78
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Scott Wlaschin
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
 
Software to the slaughter
Software to the slaughterSoftware to the slaughter
Software to the slaughterQuinn Wilton
 

Similar to Functional Programming 101 with Scala and ZIO (20)

Interesting facts on c
Interesting facts on cInteresting facts on c
Interesting facts on c
 
10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING10. funtions and closures IN SWIFT PROGRAMMING
10. funtions and closures IN SWIFT PROGRAMMING
 
Abstracting Vector Architectures in Library Generators: Case Study Convolutio...
Abstracting Vector Architectures in Library Generators: Case Study Convolutio...Abstracting Vector Architectures in Library Generators: Case Study Convolutio...
Abstracting Vector Architectures in Library Generators: Case Study Convolutio...
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
functions
functionsfunctions
functions
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹
 
Reverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading SkillsReverse Engineering Dojo: Enhancing Assembly Reading Skills
Reverse Engineering Dojo: Enhancing Assembly Reading Skills
 
Fourier project presentation
Fourier project  presentationFourier project  presentation
Fourier project presentation
 
Scaladays 2011 - The Ease of Scalaz
Scaladays 2011 - The Ease of ScalazScaladays 2011 - The Ease of Scalaz
Scaladays 2011 - The Ease of Scalaz
 
Arduino for Beginners
Arduino for BeginnersArduino for Beginners
Arduino for Beginners
 
Introduction to c part -1
Introduction to c   part -1Introduction to c   part -1
Introduction to c part -1
 
Java PSkills Session-3 PNR.pptx
Java PSkills Session-3 PNR.pptxJava PSkills Session-3 PNR.pptx
Java PSkills Session-3 PNR.pptx
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Fairplay Talk
Fairplay TalkFairplay Talk
Fairplay Talk
 
Software to the slaughter
Software to the slaughterSoftware to the slaughter
Software to the slaughter
 
Kotlin
KotlinKotlin
Kotlin
 

More from Jorge Vásquez

Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!Jorge Vásquez
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Jorge Vásquez
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
 
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIOConsiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIOJorge Vásquez
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021Jorge Vásquez
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in ScalaJorge Vásquez
 
The Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at WorkThe Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at WorkJorge Vásquez
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaJorge Vásquez
 

More from Jorge Vásquez (8)

Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
Behold! The Happy Path To Captivate Your Users With Stunning CLI Apps!
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIOConsiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
Consiguiendo superpoderes para construir aplicaciones modernas en la JVM con ZIO
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
 
Exploring type level programming in Scala
Exploring type level programming in ScalaExploring type level programming in Scala
Exploring type level programming in Scala
 
The Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at WorkThe Terror-Free Guide to Introducing Functional Scala at Work
The Terror-Free Guide to Introducing Functional Scala at Work
 
Exploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in ScalaExploring ZIO Prelude: The game changer for typeclasses in Scala
Exploring ZIO Prelude: The game changer for typeclasses in Scala
 

Recently uploaded

Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Mastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxMastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxAS Design & AST.
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxRTS corp
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdfSteve Caron
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 

Recently uploaded (20)

Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Mastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxMastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptx
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptx
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 

Functional Programming 101 with Scala and ZIO

  • 1. Functional Programming 101 with Scala and ZIO Functional World April 15th, 2021
  • 4. Agenda • Functional Programming (FP) basic concepts
  • 5. Agenda • Functional Programming (FP) basic concepts • ZIO basic concepts
  • 6. Agenda • Functional Programming (FP) basic concepts • ZIO basic concepts • Live coding: Tic-Tac-Toe game
  • 8. What is Functional Programming? Programming paradigm, where programs are a composition of pure functions
  • 10. Characteristics of a Pure Function • Total
  • 11. Characteristics of a Pure Function • Total • Deterministic and depends on its inputs only
  • 12. Characteristics of a Pure Function • Total • Deterministic and depends on its inputs only • Must not have side effects
  • 13. A Pure Function must be Total For each input that is provided to the function there must be a defined output
  • 14. A Pure Function must be Total def divide(a: Int, b: Int): Int = a / b divide(5, 0) // java.lang.ArithmeticException: / by zero
  • 15. A Pure Function must be Total def divide(a: Int, b: Int): Int = a / b divide(5, 0) // java.lang.ArithmeticException: / by zero
  • 16. A Pure Function must be Total def divide(a: Int, b: Int): Int = a / b divide(5, 0) // java.lang.ArithmeticException: / by zero
  • 17. A Pure Function must be Total def divide(a: Int, b: Int): Int = a / b divide(5, 0) // java.lang.ArithmeticException: / by zero
  • 18. A Pure Function must be Total def divide(a: Int, b: Int): Int = a / b
  • 19. A Pure Function must be Total def divide(a: Int, b: Int): Int = a / b • The signature of this function tells a lie!
  • 20. A Pure Function must be Total def divide(a: Int, b: Int): Int = a / b • The signature of this function tells a lie! • Every time we call it we will have to be very careful
  • 21. A Pure Function must be Total def divide(a: Int, b: Int): Int = a / b • The signature of this function tells a lie! • Every time we call it we will have to be very careful • Runtime exceptions can happen. The compiler is not able to do anything to help us to avoid this
  • 22. A Pure Function must be Total def divide(a: Int, b: Int): Option[Int] = if (b != 0) Some(a / b) else None divide(5, 0) // None
  • 23. A Pure Function must be Total def divide(a: Int, b: Int): Option[Int] = if (b != 0) Some(a / b) else None divide(5, 0) // None
  • 24. A Pure Function must be Total def divide(a: Int, b: Int): Option[Int] = if (b != 0) Some(a / b) else None divide(5, 0) // None
  • 25. A Pure Function must be Total def divide(a: Int, b: Int): Option[Int] = if (b != 0) Some(a / b) else None divide(5, 0) // None
  • 26. A Pure Function must be Total def divide(a: Int, b: Int): Option[Int] = if (b != 0) Some(a / b) else None
  • 27. A Pure Function must be Total def divide(a: Int, b: Int): Option[Int] = if (b != 0) Some(a / b) else None • The function’s signature clearly communicates that some inputs are not handled
  • 28. A Pure Function must be Total def divide(a: Int, b: Int): Option[Int] = if (b != 0) Some(a / b) else None • The function’s signature clearly communicates that some inputs are not handled • The compiler will force us to consider the case in which the result is not defined
  • 29. A Pure Function must be Total def divide(a: Int, b: Int): Option[Int] = if (b != 0) Some(a / b) else None • The function’s signature clearly communicates that some inputs are not handled • The compiler will force us to consider the case in which the result is not defined • No runtime exceptions!
  • 30. A Pure Function must be Deterministic and depend only on its inputs For each input that is provided to the function, the same output must be returned, no matter how many times the function is called
  • 31. A Pure Function must be Deterministic and depend only on its inputs def generateRandomInt(): Int = (new scala.util.Random).nextInt generateRandomInt() // Result: -272770531 generateRandomInt() // Result: 217937820
  • 32. A Pure Function must be Deterministic and depend only on its inputs def generateRandomInt(): Int = (new scala.util.Random).nextInt generateRandomInt() // Result: -272770531 generateRandomInt() // Result: 217937820
  • 33. A Pure Function must be Deterministic and depend only on its inputs def generateRandomInt(): Int = (new scala.util.Random).nextInt generateRandomInt() // Result: -272770531 generateRandomInt() // Result: 217937820
  • 34. A Pure Function must be Deterministic and depend only on its inputs def generateRandomInt(): Int = (new scala.util.Random).nextInt generateRandomInt() // Result: -272770531 generateRandomInt() // Result: 217937820
  • 35. A Pure Function must be Deterministic and depend only on its inputs def generateRandomInt(): Int = (new scala.util.Random).nextInt
  • 36. A Pure Function must be Deterministic and depend only on its inputs def generateRandomInt(): Int = (new scala.util.Random).nextInt • Clearly not deterministic!
  • 37. A Pure Function must be Deterministic and depend only on its inputs def generateRandomInt(): Int = (new scala.util.Random).nextInt • Clearly not deterministic! • The signature is misleading, because there is a hidden dependency on a scala.util.Random object
  • 38. A Pure Function must be Deterministic and depend only on its inputs def generateRandomInt(): Int = (new scala.util.Random).nextInt • Clearly not deterministic! • The signature is misleading, because there is a hidden dependency on a scala.util.Random object • Difficult to test because we can never really be sure how the function will behave
  • 39. A Pure Function must be Deterministic and depend only on its inputs final case class RNG(seed: Long) { def nextInt: (Int, RNG) = { val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL val nextRNG = RNG(newSeed) val n = (newSeed >>> 16).toInt (n, nextRNG) } } def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt val random = RNG(10) val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181) val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181) val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
  • 40. A Pure Function must be Deterministic and depend only on its inputs final case class RNG(seed: Long) { def nextInt: (Int, RNG) = { val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL val nextRNG = RNG(newSeed) val n = (newSeed >>> 16).toInt (n, nextRNG) } } def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt val random = RNG(10) val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181) val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181) val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
  • 41. A Pure Function must be Deterministic and depend only on its inputs final case class RNG(seed: Long) { def nextInt: (Int, RNG) = { val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL val nextRNG = RNG(newSeed) val n = (newSeed >>> 16).toInt (n, nextRNG) } } def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt val random = RNG(10) val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181) val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181) val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
  • 42. A Pure Function must be Deterministic and depend only on its inputs final case class RNG(seed: Long) { def nextInt: (Int, RNG) = { val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL val nextRNG = RNG(newSeed) val n = (newSeed >>> 16).toInt (n, nextRNG) } } def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt val random = RNG(10) val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181) val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181) val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
  • 43. A Pure Function must be Deterministic and depend only on its inputs final case class RNG(seed: Long) { def nextInt: (Int, RNG) = { val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL val nextRNG = RNG(newSeed) val n = (newSeed >>> 16).toInt (n, nextRNG) } } def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt val random = RNG(10) val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181) val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181) val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
  • 44. A Pure Function must be Deterministic and depend only on its inputs final case class RNG(seed: Long) { def nextInt: (Int, RNG) = { val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL val nextRNG = RNG(newSeed) val n = (newSeed >>> 16).toInt (n, nextRNG) } } def generateRandomInt(random: RNG): (Int, RNG) = random.nextInt val random = RNG(10) val (n1, random1) = generateRandomInt(random) // n1 = 3847489, random1 = RNG(252149039181) val (n2, random2) = generateRandomInt(random) // n2 = 3847489, random2 = RNG(252149039181) val (n3, random3) = generateRandomInt(random2) // n3 = 1334288366, random3 = RNG(87443922374356)
  • 45. A Pure Function must not have side effects Finally, a function must not have any side effects:
  • 46. A Pure Function must not have side effects Finally, a function must not have any side effects: • Memory mutations
  • 47. A Pure Function must not have side effects Finally, a function must not have any side effects: • Memory mutations • Interactions with the outside world, such as:
  • 48. A Pure Function must not have side effects Finally, a function must not have any side effects: • Memory mutations • Interactions with the outside world, such as: • Printing messages to the console
  • 49. A Pure Function must not have side effects Finally, a function must not have any side effects: • Memory mutations • Interactions with the outside world, such as: • Printing messages to the console • Calling an external API
  • 50. A Pure Function must not have side effects Finally, a function must not have any side effects: • Memory mutations • Interactions with the outside world, such as: • Printing messages to the console • Calling an external API • Querying a database
  • 51. A Pure Function must not have side effects A pure function can only:
  • 52. A Pure Function must not have side effects A pure function can only: • Work with immutable values
  • 53. A Pure Function must not have side effects A pure function can only: • Work with immutable values • Return an output for a corresponding input
  • 54. A Pure Function must not have side effects var a = 0 def increment(inc: Int): Int = { a + = inc a }
  • 55. A Pure Function must not have side effects def add(a: Int, b: Int): Int = { println(s "Adding two integers: $a and $b") a + b }
  • 57. FP vs. OOP • Variables: Immutable / Mutable
  • 58. FP vs. OOP • Variables: Immutable / Mutable • Side effects: NO / YES
  • 59. FP vs. OOP • Variables: Immutable / Mutable • Side effects: NO / YES • Iterations: Recursion / Loops
  • 61. FP vs. OOP • State: Flows through pure functions / Shared by several objects
  • 62. FP vs. OOP • State: Flows through pure functions / Shared by several objects • Key elements: Immutable values and Functions / Objects and Methods
  • 63. FP vs. OOP • State: Flows through pure functions / Shared by several objects • Key elements: Immutable values and Functions / Objects and Methods • Suitable for Parallel programming: YES / Not so much
  • 66. Benefits of Functional Programming • Local reasoning • Referential transparency -> Fearless refactoring!
  • 67. Benefits of Functional Programming • Local reasoning • Referential transparency -> Fearless refactoring! • Conciseness -> Fewer bugs!
  • 70. Benefits of Functional Programming • Easier to test • Applications behave more predictably
  • 71. Benefits of Functional Programming • Easier to test • Applications behave more predictably • Allows us to write correct parallel programs
  • 72.
  • 73.
  • 75. Functional Effects • Descriptions of interactions with the outside world
  • 76. Functional Effects • Descriptions of interactions with the outside world • Immutable values that can serve as inputs and outputs of pure functions
  • 77. Functional Effects • Descriptions of interactions with the outside world • Immutable values that can serve as inputs and outputs of pure functions • They are executed only at the End of the World
  • 78.
  • 80. ZIO - The Library Allows us to build modern applications, using the principles of Functional Programming!
  • 81. ZIO - The Library
  • 82. ZIO - The Library • Asynchronous & Concurrent -> Fiber-based model!
  • 83. ZIO - The Library • Asynchronous & Concurrent -> Fiber-based model! • Resilient -> Leverages the power of Scala's Type System!
  • 84. ZIO - The Library • Asynchronous & Concurrent -> Fiber-based model! • Resilient -> Leverages the power of Scala's Type System! • Efficient -> Apps that never leak resources!
  • 85. ZIO - The Library • Asynchronous & Concurrent -> Fiber-based model! • Resilient -> Leverages the power of Scala's Type System! • Efficient -> Apps that never leak resources! • Easy to understand and test -> Thanks to superior composability!
  • 86. ZIO - The Data Type ZIO[-R, +E, +A]
  • 87. ZIO - The Data Type ZIO[-R, +E, +A] • Core type of the ZIO Library
  • 88. ZIO - The Data Type ZIO[-R, +E, +A] • Core type of the ZIO Library • Functional Effect
  • 89. ZIO - The Data Type A good mental model is the following: R => Either[E, A] This means that a ZIO effect:
  • 90. ZIO - The Data Type A good mental model is the following: R => Either[E, A] This means that a ZIO effect: • Needs an environment of type R to run
  • 91. ZIO - The Data Type A good mental model is the following: R => Either[E, A] This means that a ZIO effect: • Needs an environment of type R to run • It may fail with an error of type E
  • 92. ZIO - The Data Type A good mental model is the following: R => Either[E, A] This means that a ZIO effect: • Needs an environment of type R to run • It may fail with an error of type E • Or it may complete successfully, returning a value of type A
  • 93. ZIO - The Data Type Common aliases: Task[+A] = ZIO[Any, Throwable, +A] UIO[+A] = ZIO[Any, Nothing, +A] RIO[-R, +A] = ZIO[-R, Throwable, +A] IO[+E, +A] = ZIO[Any, E, A] URIO[-R, +A] = ZIO[R, Nothing, A]
  • 94. Live coding Tic-Tac-Toe game with ZIO! https://github.com/jorge-vasquez-2301/zio-tictactoe
  • 95. Where to learn more • Introduction to Programming with ZIO Functional Effects - Scalac Blog • Introducción a la Programación con Efectos Funcionales usando ZIO - Scalac Blog • Mastering modularity in ZIO with ZLayer - Scalac Blog • How to write a (completely lock-free) concurrent LRU Cache with ZIO STM • ZIO Official Site • Zionomicon
  • 96. Where to learn more Learn how to use the full potential of Functional Programming with Scalac Trainings! • Scala 2 for Java Developers • Scala 3 for Scala 2 Developers • ZIO