What are monads?
@jlgarhdez
slides
But rst...
What is functional programming?
Functional programming!
A programming paradigm that:
treats functions as rst class citicens
encourages immutability
avoids global state
makes your code honest
Avoids side effects (encourages purity)
What are side effects?
Everything that your code does, apart of operating
with values.
How can we implement this?
public int sum(Int a, Int b) {
// ???
}
public int sum(int a, int b) {
launchMissiles(); // Side effect!
return a + b;
}
public int sum(int a, int b) {
this.pass = 4; // Side effect!
return a + b;
}
public int sum(int a, int b) {
throw new Exception("message"); // Side effect!
return a + b;
}
More bits of FP
Imagine this
class IO {
def read(): String = readLine()// reads from standard input
def write(text: String): Unit = println(text)// writes to stan
}
you could use it in the following way:
def hello(): String = {
write("what is your name?")
val name = read()
val hello = "hello" + name
write(hello)
return hello
}
The good part:
That that code is idiomatic and concise!
The bad part:
That code is not pure! (has side effects)
How can we x this?
Transform this
class IO {
def read(): String = readLine()
def write(text: String): Unit = println(text)
}
Into this!
This is our small IO language
trait IO[A]
case class Read() extends IO[String]
case class Write(str: String) extends IO[Unit]
This kind of construction is called Algebraic Data
Type.
Interpreter
Since our previous ADT is not effectful, meaning that
can not execute side effects, we need its companion,
the interpreter!
def interpret(op: IO[A]): A = op match {
case Read() => readLine()
case Write(text) => printLn(text)
}
Now, let's write our hello
function!
def pureHello(): IO[String] = {
Write("what is your name?")
val name: IO[String] = Read()
Write("hello" + name) // ERROR!, you can not concat
// String and IO[String]
}
How can we x it?
Lets add a way to sequence IO operations to our
ADT!
trait IO[A]
case class Read() extends IO[String]
case class Write(str: String) extends IO[Unit]
case class Sequence[A, B](
fa: IO[A],
fn: A => IO[B])
extends IO[B]
Can we write hello now?
def pureHello: IO[String] = {
Sequence(
Write("What is your name?"),
(_) => {
Sequence(
Read(),
(name) => {
Write("hello, " + name)
}
)
})
}
We can't! we are returning an IO[Unit] , because of
the last Write() ... Lets x that!
Add another case to our ADT
Let's add a way to put values inside IO
trait IO[A]
case class Read() extends IO[String]
case class Write(str: String) extends IO[Unit]
case class Sequence[A, B](
fa: IO[A],
fn: A => IO[B]) extends IO[B]
case class Point[A](a: A) extends IO[A]
Finally, we can write it now!
def pureHello: IO[String] = {
Sequence(
Write("What is your name?"),
(_) => {
Sequence(
Read(),
(name) => {
Sequence(
Write("hello, " + name),
(_) => {
Point("hello, " + name)
}
)
}
)
})
}
The good parts
That code is pure!
The bad parts
THAT CODE IS UGLY
Let's x that!
Introducing TypeClasses
Typeclasses are a way to give more behaviour to an
class. You can think of them like interfaces in OOP.
But better
Much better
Some typeclasses
trait Eq[A] {
def equals(a: A, b: A): Bool
}
val intEquality = new Eq[Int] {
def equals(a: Int, b: Int) = a == b
}
trait Show[A] {
def show(a: A): String
}
val showInt = new ToString[Int] {
def show(a: Int) = a.toString
}
Guess what?
Monad is a typeclass!
What are monads?
What are monads?
Monad
trait Monad[M[_]] {
def point[A](a: A): M[A]
def flatMap[A, B](ma: M[A])(fn: A => M[B]): M[B]
}
What are monads?
Monad is a typeclass for de ning imperative
languages.
Back to our IO example
Remember all the weirdness we needed to do in
order to do our pureHello function?
We are really close to simplifying it a lot!
Let's create a Monad instance for our IO language
rst!
val ioMonad = new Monad[IO] {
def point[A](a: A): IO[A] = Point(a)
def flatMap[A, B](ma: IO[A])(fn: A => IO[B]): IO[B] =
Sequence(ma, fn)
}
Now, let's rewrite our
pureHello
def pureHello: IO[String] = for {
_ <- Write("What's your name?")
name <- Read()
_ <- Write("Hello, " + name)
} yield "Hello, " + name
We only need to review our interpreter...
New interpreter
def ioInterp[A](op: IO[A]): A = op match {
case Write(text) => println(text)
case Read() => readLine()
case Point(x) => x
case Sequence(x, fn) => ioInterp(fn(ioInterp(x)))
}
And, combine!
ioInterp(pureHello()) // this actually does IO
// thanks to the interpreter
Small recap
Functional programming is cool
Typeclasses are here to help
Monad is for imperative programming
Monads + Interpreters = WIN!
We are done,
thanks!
@jlgarhdez
meetup.com/FP-Madrid/
meetup.com/Haskell-MAD/

More Related Content

PPTX
Introduction to C++
PPTX
Introduction to c++
PPT
JAVA Variables and Operators
PPTX
Polymorphism in c++(ppt)
PDF
Introduction to cpp
PDF
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Introduction to C++
Introduction to c++
JAVA Variables and Operators
Polymorphism in c++(ppt)
Introduction to cpp
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]

What's hot (20)

PPTX
Python programming workshop session 1
PPTX
C Theory
PDF
C++ book
DOCX
Diff between c and c++
PPTX
Learning C++ - Introduction to c++ programming 1
PPTX
Intro to c++
PPT
C++: inheritance, composition, polymorphism
PPT
Python Part 1
PPTX
Virtual function in C++ Pure Virtual Function
PPT
Lecture01
PPT
Java 8 - CJ
PPTX
Python workshop session 6
PPT
Introduction to C++
PPTX
C introduction by thooyavan
PDF
01. introduction to C++
PPTX
Python programming workshop session 3
PPTX
Python programming workshop session 2
PPTX
Polymorphism in C++
PPT
PDF
Lecture 3 getting_started_with__c_
Python programming workshop session 1
C Theory
C++ book
Diff between c and c++
Learning C++ - Introduction to c++ programming 1
Intro to c++
C++: inheritance, composition, polymorphism
Python Part 1
Virtual function in C++ Pure Virtual Function
Lecture01
Java 8 - CJ
Python workshop session 6
Introduction to C++
C introduction by thooyavan
01. introduction to C++
Python programming workshop session 3
Python programming workshop session 2
Polymorphism in C++
Lecture 3 getting_started_with__c_
Ad

Similar to What are monads? (20)

PPTX
Functional IO and Effects
PPTX
ZIO: Powerful and Principled Functional Programming in Scala
PDF
Generic Functional Programming with Type Classes
PDF
The Death of Final Tagless
PDF
pure-functional-programming.pdf
PPTX
Scala for curious
PDF
Introducing Monads and State Monad at PSUG
PDF
Drinking the free kool-aid
PDF
Purely Functional I/O
PDF
PDF
Simple IO Monad in 'Functional Programming in Scala'
PDF
Meet scala
PDF
Practical cats
PPT
Scala - brief intro
PDF
Railroading into Scala
PDF
Oh, All the things you'll traverse
PDF
Scala: Object-Oriented Meets Functional, by Iulian Dragos
PDF
Scala for Java Developers
ODP
Functional programming with Scala
PDF
Functional programming in Scala
Functional IO and Effects
ZIO: Powerful and Principled Functional Programming in Scala
Generic Functional Programming with Type Classes
The Death of Final Tagless
pure-functional-programming.pdf
Scala for curious
Introducing Monads and State Monad at PSUG
Drinking the free kool-aid
Purely Functional I/O
Simple IO Monad in 'Functional Programming in Scala'
Meet scala
Practical cats
Scala - brief intro
Railroading into Scala
Oh, All the things you'll traverse
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala for Java Developers
Functional programming with Scala
Functional programming in Scala
Ad

Recently uploaded (20)

PDF
Cost to Outsource Software Development in 2025
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
The Dynamic Duo Transforming Financial Accounting Systems Through Modern Expe...
PDF
Time Tracking Features That Teams and Organizations Actually Need
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
DNT Brochure 2025 – ISV Solutions @ D365
PDF
DuckDuckGo Private Browser Premium APK for Android Crack Latest 2025
PPTX
"Secure File Sharing Solutions on AWS".pptx
DOCX
How to Use SharePoint as an ISO-Compliant Document Management System
PDF
CCleaner 6.39.11548 Crack 2025 License Key
PPTX
CNN LeNet5 Architecture: Neural Networks
PPTX
Weekly report ppt - harsh dattuprasad patel.pptx
PDF
iTop VPN Crack Latest Version Full Key 2025
PDF
Topaz Photo AI Crack New Download (Latest 2025)
PDF
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
PDF
Website Design Services for Small Businesses.pdf
PPTX
Computer Software - Technology and Livelihood Education
PDF
Types of Token_ From Utility to Security.pdf
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
PDF
Visual explanation of Dijkstra's Algorithm using Python
Cost to Outsource Software Development in 2025
Designing Intelligence for the Shop Floor.pdf
The Dynamic Duo Transforming Financial Accounting Systems Through Modern Expe...
Time Tracking Features That Teams and Organizations Actually Need
Computer Software and OS of computer science of grade 11.pptx
DNT Brochure 2025 – ISV Solutions @ D365
DuckDuckGo Private Browser Premium APK for Android Crack Latest 2025
"Secure File Sharing Solutions on AWS".pptx
How to Use SharePoint as an ISO-Compliant Document Management System
CCleaner 6.39.11548 Crack 2025 License Key
CNN LeNet5 Architecture: Neural Networks
Weekly report ppt - harsh dattuprasad patel.pptx
iTop VPN Crack Latest Version Full Key 2025
Topaz Photo AI Crack New Download (Latest 2025)
AI-Powered Threat Modeling: The Future of Cybersecurity by Arun Kumar Elengov...
Website Design Services for Small Businesses.pdf
Computer Software - Technology and Livelihood Education
Types of Token_ From Utility to Security.pdf
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
Visual explanation of Dijkstra's Algorithm using Python

What are monads?

  • 3. What is functional programming?
  • 4. Functional programming! A programming paradigm that: treats functions as rst class citicens encourages immutability avoids global state makes your code honest Avoids side effects (encourages purity)
  • 5. What are side effects? Everything that your code does, apart of operating with values.
  • 6. How can we implement this? public int sum(Int a, Int b) { // ??? }
  • 7. public int sum(int a, int b) { launchMissiles(); // Side effect! return a + b; } public int sum(int a, int b) { this.pass = 4; // Side effect! return a + b; } public int sum(int a, int b) { throw new Exception("message"); // Side effect! return a + b; }
  • 9. Imagine this class IO { def read(): String = readLine()// reads from standard input def write(text: String): Unit = println(text)// writes to stan } you could use it in the following way: def hello(): String = { write("what is your name?") val name = read() val hello = "hello" + name write(hello) return hello }
  • 10. The good part: That that code is idiomatic and concise! The bad part: That code is not pure! (has side effects)
  • 11. How can we x this?
  • 12. Transform this class IO { def read(): String = readLine() def write(text: String): Unit = println(text) }
  • 13. Into this! This is our small IO language trait IO[A] case class Read() extends IO[String] case class Write(str: String) extends IO[Unit] This kind of construction is called Algebraic Data Type.
  • 14. Interpreter Since our previous ADT is not effectful, meaning that can not execute side effects, we need its companion, the interpreter! def interpret(op: IO[A]): A = op match { case Read() => readLine() case Write(text) => printLn(text) }
  • 15. Now, let's write our hello function! def pureHello(): IO[String] = { Write("what is your name?") val name: IO[String] = Read() Write("hello" + name) // ERROR!, you can not concat // String and IO[String] }
  • 16. How can we x it? Lets add a way to sequence IO operations to our ADT! trait IO[A] case class Read() extends IO[String] case class Write(str: String) extends IO[Unit] case class Sequence[A, B]( fa: IO[A], fn: A => IO[B]) extends IO[B]
  • 17. Can we write hello now? def pureHello: IO[String] = { Sequence( Write("What is your name?"), (_) => { Sequence( Read(), (name) => { Write("hello, " + name) } ) }) } We can't! we are returning an IO[Unit] , because of the last Write() ... Lets x that!
  • 18. Add another case to our ADT Let's add a way to put values inside IO trait IO[A] case class Read() extends IO[String] case class Write(str: String) extends IO[Unit] case class Sequence[A, B]( fa: IO[A], fn: A => IO[B]) extends IO[B] case class Point[A](a: A) extends IO[A]
  • 19. Finally, we can write it now! def pureHello: IO[String] = { Sequence( Write("What is your name?"), (_) => { Sequence( Read(), (name) => { Sequence( Write("hello, " + name), (_) => { Point("hello, " + name) } ) } ) }) }
  • 20. The good parts That code is pure! The bad parts THAT CODE IS UGLY
  • 22. Introducing TypeClasses Typeclasses are a way to give more behaviour to an class. You can think of them like interfaces in OOP. But better Much better
  • 23. Some typeclasses trait Eq[A] { def equals(a: A, b: A): Bool } val intEquality = new Eq[Int] { def equals(a: Int, b: Int) = a == b } trait Show[A] { def show(a: A): String } val showInt = new ToString[Int] { def show(a: Int) = a.toString }
  • 25. Monad is a typeclass!
  • 28. Monad trait Monad[M[_]] { def point[A](a: A): M[A] def flatMap[A, B](ma: M[A])(fn: A => M[B]): M[B] }
  • 29. What are monads? Monad is a typeclass for de ning imperative languages.
  • 30. Back to our IO example Remember all the weirdness we needed to do in order to do our pureHello function? We are really close to simplifying it a lot! Let's create a Monad instance for our IO language rst! val ioMonad = new Monad[IO] { def point[A](a: A): IO[A] = Point(a) def flatMap[A, B](ma: IO[A])(fn: A => IO[B]): IO[B] = Sequence(ma, fn) }
  • 31. Now, let's rewrite our pureHello def pureHello: IO[String] = for { _ <- Write("What's your name?") name <- Read() _ <- Write("Hello, " + name) } yield "Hello, " + name We only need to review our interpreter...
  • 32. New interpreter def ioInterp[A](op: IO[A]): A = op match { case Write(text) => println(text) case Read() => readLine() case Point(x) => x case Sequence(x, fn) => ioInterp(fn(ioInterp(x))) }
  • 33. And, combine! ioInterp(pureHello()) // this actually does IO // thanks to the interpreter
  • 34. Small recap Functional programming is cool Typeclasses are here to help Monad is for imperative programming Monads + Interpreters = WIN!