SlideShare una empresa de Scribd logo
1 de 29
Descargar para leer sin conexión
A Tale of Two Monads: Category-theoretic and
Computational viewpoints
Liang-Ting Chen
What is … a monad?
Functional Programmer:
What is … a monad?
Functional Programmer:
• a warm, fuzzy, little thing

Monica Monad, by FalconNL
What is … a monad?
Functional Programmer:
• a warm, fuzzy, little thing
• return and bind with monad
laws

class Monad m where	
(>>=) ::m a->(a -> m b)->m b
return::a ->m a	
!

-- monad laws 	
return a >>= k = k a	
m >>= return = m	
m >>= (x-> k x >>= h) =

(m >>= k) >>= h
•

•

What is … a monad?
Functional Programmer:
• a warm, fuzzy, little thing
• return and bind with monad
laws
• a programmable semicolon

do { x' <- return x; f x’} 

≡ do { f x }

do { x <- m; return x }

≡ do { m }


•

do { y <- do { x <- m; f x }
g y }

≡ do { x <- m; do { y <- f
x; g y }}

≡ do { x <- m; y <- f x; g y
}
Kleisli Triple
T : Obj(C) ! Obj(C)
⌘A : A ! T A
⇤
( ) : hom(A, T B) ! hom(T A, T B)

What is … a monad?
Functional Programmer:
• a warm, fuzzy, little thing
• return and bind with monad
laws
• a programmable semicolon
• E. Moggi, “Notions of
computation and monads”, 1991

`M :
(return)
` [M ]T : T

` M : T⌧
x:⌧ `N :T
(bind)
` letT (x ( M ) in N : T

monad laws
⇤
⌘A
⇤

= id T A
⌘A ; f = f
⇤ ⇤
⇤
f ; g = (f ; g)
“Hey, mathematician! What is a monad?”,

you asked.
“A monad in X is just a monoid in the category
of endofunctors of X, what’s the problem?”
–Philip Wadler
“A monad in X is just a monoid in the category
of endofunctors of X, what’s the problem?”
–James Iry, A Brief, Incomplete and Mostly Wrong History of
Programming Languages
“A monad in X is just a monoid in the category
of endofunctors of X, with product × replaced
by composition of endofunctors and unit set by
the identity endofunctor.”
–Saunders Mac Lane, Categories for the Working Mathematician, p.138
monad on a category

What is … a monad?
Mathematician:
• a monoid in the category of
endofunctors

T: C !C
⌘ : I !T
˙
µ : T 2 !T
˙

monad laws

T

3

Tµ

/ T2
µ

µT

✏
T2

T

T⌘

µ

✏
/T

2

/T o

⌘T

µ
id

✏ ~
T

id

T
monad in a bicategory
• 0-cell a;

What is … a monad?
Mathematician:
• a monoid in the category of
endofunctors
• a monoid in the endomorphism
category K(a,a) of a bicategory K

• 1-cell t : a ! a;
• 2-cell ⌘ : 1a ! t, and µ : tt ! t

monad laws
ttt

tµ

/ tt t
µ

µt

✏
tt

µ

✏
/t

t⌘

/ tt o

⌘t

µ
id

✏ 
t

id

t
What is … a monad?
Mathematician:
• a monoid in the category of
endofunctors
• a monoid in the endomorphism
category K(a,a) of a bicategory K
• …

from Su Horng’s slide
Monads in Haskell, the Abstract Ones
•

class Functor m => Monad m where

unit :: a -> m a -- η 

join :: m (m a) -> m a -- μ	

•

--join . (fmap join) = join . join

--join . (fmap unit) = join . unit = id
T

3

Tµ

/T

2
µ

µT

✏
T2

µ

✏
/T

T

T⌘

2

/T o

⌘T

µ
id

✏ ~
T

id

T
Kleisli Triples and Monads are Equivalent (Manes 1976)
fmap :: Monad m => (a -> b) -> m a -> m b

fmap f x = x >>= return . f


•



join :: Monad m => m (m a) -> m a

join x = x >>= id

-- id :: m a -> m a
Kleisli Triples and Monads are Equivalent (Manes 1976)
fmap :: Monad m => (a -> b) -> m a -> m b

fmap f x = x >>= return . f


•



join :: Monad m => m (m a) -> m a

join x = x >>= id

-- id :: m a -> m a
•

(>>=) :: Monad m => m a -> (a -> m b) -> m b

x >>= f = join (fmap f x)

-- fmap f :: m a -> m (m b)
Monads are derivable from algebraic
operations and equations if and only if they
have finite rank.
–G. M. Kelly and A. J. Power, Adjunctions whose counits are
coequalizers, and presentations of finitary enriched monads, 1993.
An Algebraic Theory: Monoid
• a set M with
• a nullary operation ✏ : 1 ! M
• a binary operation • : M ⇥ M ! M
satisfying
• associativity: (a • b) • c = a • (b • c)
• identity: a • ✏ = ✏ • a = a
Monoids in Haskell:
class Monoid a where	
mempty :: a	
-- ^ Identity of 'mappend'	
mappend :: a -> a -> a	
-- ^ An associative operation	
!

instance Monoid [a] where	
mempty = []	
mappend = (++)	
!

instance Monoid b => Monoid (a -> b) where	
mempty _ = mempty	
mappend f g x = f x `mappend` g x
An Algebraic Theory: Semi-lattice
• a set L with
• a binary operation _ : M ⇥ M ! M
satisfying
• commutativity: a _ b = b _ a
• associativity: a _ (b _ c) = (a _ b) _ c
• idenpotency: a _ a = a
Semi-lattices in Haskell
class SemiLattice a where	
join :: a -> a -> a	
!

instance SemiLattice Bool where	
join = (||)	
!

instance SemiLattice v => SemiLattice (k -> v) where	
f `join` g = x -> f x `join` g x	
!

instance SemiLattice IntSet where	
join = union
An Algebraic Theory (defined as a type class in Haskell)

• a set of operations

2 ⌃ and ar( ) 2 N

• a set of equations with variables, e.g.

1 ( 1 (x, y), z)

=

1 (x,

1 (y, z))
A Model of an Algebraic Theory (an instance)

• a set M with
• an n-ary function M for each operation
satisfying each equation

with ar( ) = n
A Monad with Finite Rank

MX =

[

{ M i[M S] | i : S ✓f X }

(M i : M S ! M X)
Examples of Algebraic Effects

•

maybe X 7! X + 1

•

exceptions X 7! X + E

•

nondeterminism X 7! Pfin (X)

•

side-effects X 7! (X ⇥ State)

State

but continuations is not algebraic X 7! R

(RX )
Algebraic Theory of Exception
• nullary operations raisee for each e 2 E
• no equations

A monadic program
f :: A -> B + E	
corresponds to a homomorphism between free algebras
Why Algebraic Effects?

•

Various ways of combination, e.g. sum, product,
distribution, etc.

•

Equational reasoning of monadic programming is simpler.

•

A classification of effects: a deeper insight.
Conclusion

•

Moggi’s formulation solves fundamental problems, e.g. a
unified approach to I/O.

•

Mathematicians bring new ideas to functional
programming, e.g. algebraic effects, modular
construction of effects

•

Still an ongoing area
Conclusion

•

Moggi’s formulation solves fundamental problems, e.g. a
unified approach to I/O.

•

Mathematicians bring new ideas to functional
programming, e.g. algebraic effects, modular
construction of effects

•

Still an ongoing area

Más contenido relacionado

La actualidad más candente

Eighan values and diagonalization
Eighan values and diagonalization Eighan values and diagonalization
Eighan values and diagonalization gandhinagar
 
Eigenvalues and eigenvectors
Eigenvalues and eigenvectorsEigenvalues and eigenvectors
Eigenvalues and eigenvectorsiraq
 
Eigen value , eigen vectors, caley hamilton theorem
Eigen value , eigen vectors, caley hamilton theoremEigen value , eigen vectors, caley hamilton theorem
Eigen value , eigen vectors, caley hamilton theoremgidc engineering college
 
Eigen values and eigen vectors
Eigen values and eigen vectorsEigen values and eigen vectors
Eigen values and eigen vectorsRiddhi Patel
 
derogatory and non derogatory matrices
derogatory and non derogatory matricesderogatory and non derogatory matrices
derogatory and non derogatory matricesKomal Singh
 
Eigen values and eigenvectors
Eigen values and eigenvectorsEigen values and eigenvectors
Eigen values and eigenvectorsAmit Singh
 
Eigen value and eigen vector
Eigen value and eigen vectorEigen value and eigen vector
Eigen value and eigen vectorRutvij Patel
 
Eigen values and eigen vectors engineering
Eigen values and eigen vectors engineeringEigen values and eigen vectors engineering
Eigen values and eigen vectors engineeringshubham211
 
Seismic data processing (mathematical foundations)
Seismic data processing (mathematical foundations)Seismic data processing (mathematical foundations)
Seismic data processing (mathematical foundations)Amin khalil
 
Linear Algebra and Matrix
Linear Algebra and MatrixLinear Algebra and Matrix
Linear Algebra and Matrixitutor
 
Maths-->>Eigenvalues and eigenvectors
Maths-->>Eigenvalues and eigenvectorsMaths-->>Eigenvalues and eigenvectors
Maths-->>Eigenvalues and eigenvectorsJaydev Kishnani
 
Stability criterion of periodic oscillations in a (11)
Stability criterion of periodic oscillations in a (11)Stability criterion of periodic oscillations in a (11)
Stability criterion of periodic oscillations in a (11)Alexander Decker
 
Applied numerical methods lec13
Applied numerical methods lec13Applied numerical methods lec13
Applied numerical methods lec13Yasser Ahmed
 
Eigenvalues and Eigenvectors
Eigenvalues and EigenvectorsEigenvalues and Eigenvectors
Eigenvalues and EigenvectorsVinod Srivastava
 
Eigenvalues and Eigenvectors (Tacoma Narrows Bridge video included)
Eigenvalues and Eigenvectors (Tacoma Narrows Bridge video included)Eigenvalues and Eigenvectors (Tacoma Narrows Bridge video included)
Eigenvalues and Eigenvectors (Tacoma Narrows Bridge video included)Prasanth George
 
Numerical Methods - Power Method for Eigen values
Numerical Methods - Power Method for Eigen valuesNumerical Methods - Power Method for Eigen values
Numerical Methods - Power Method for Eigen valuesDr. Nirav Vyas
 

La actualidad más candente (20)

Eigenvalues
EigenvaluesEigenvalues
Eigenvalues
 
Eighan values and diagonalization
Eighan values and diagonalization Eighan values and diagonalization
Eighan values and diagonalization
 
Eigen value and vectors
Eigen value and vectorsEigen value and vectors
Eigen value and vectors
 
Eigenvalues and eigenvectors
Eigenvalues and eigenvectorsEigenvalues and eigenvectors
Eigenvalues and eigenvectors
 
Eigen value , eigen vectors, caley hamilton theorem
Eigen value , eigen vectors, caley hamilton theoremEigen value , eigen vectors, caley hamilton theorem
Eigen value , eigen vectors, caley hamilton theorem
 
Eigen values and eigen vectors
Eigen values and eigen vectorsEigen values and eigen vectors
Eigen values and eigen vectors
 
Unit ii
Unit iiUnit ii
Unit ii
 
derogatory and non derogatory matrices
derogatory and non derogatory matricesderogatory and non derogatory matrices
derogatory and non derogatory matrices
 
Eigen values and eigenvectors
Eigen values and eigenvectorsEigen values and eigenvectors
Eigen values and eigenvectors
 
Eigen value and eigen vector
Eigen value and eigen vectorEigen value and eigen vector
Eigen value and eigen vector
 
Eigen values and eigen vectors engineering
Eigen values and eigen vectors engineeringEigen values and eigen vectors engineering
Eigen values and eigen vectors engineering
 
Seismic data processing (mathematical foundations)
Seismic data processing (mathematical foundations)Seismic data processing (mathematical foundations)
Seismic data processing (mathematical foundations)
 
Linear Algebra and Matrix
Linear Algebra and MatrixLinear Algebra and Matrix
Linear Algebra and Matrix
 
Analytic function
Analytic functionAnalytic function
Analytic function
 
Maths-->>Eigenvalues and eigenvectors
Maths-->>Eigenvalues and eigenvectorsMaths-->>Eigenvalues and eigenvectors
Maths-->>Eigenvalues and eigenvectors
 
Stability criterion of periodic oscillations in a (11)
Stability criterion of periodic oscillations in a (11)Stability criterion of periodic oscillations in a (11)
Stability criterion of periodic oscillations in a (11)
 
Applied numerical methods lec13
Applied numerical methods lec13Applied numerical methods lec13
Applied numerical methods lec13
 
Eigenvalues and Eigenvectors
Eigenvalues and EigenvectorsEigenvalues and Eigenvectors
Eigenvalues and Eigenvectors
 
Eigenvalues and Eigenvectors (Tacoma Narrows Bridge video included)
Eigenvalues and Eigenvectors (Tacoma Narrows Bridge video included)Eigenvalues and Eigenvectors (Tacoma Narrows Bridge video included)
Eigenvalues and Eigenvectors (Tacoma Narrows Bridge video included)
 
Numerical Methods - Power Method for Eigen values
Numerical Methods - Power Method for Eigen valuesNumerical Methods - Power Method for Eigen values
Numerical Methods - Power Method for Eigen values
 

Destacado

Monad as things to do
Monad as things to doMonad as things to do
Monad as things to do悠滋 山本
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8JavaDayUA
 
Category Theory for Mortal Programmers
Category Theory for Mortal ProgrammersCategory Theory for Mortal Programmers
Category Theory for Mortal ProgrammersStephan February
 
Functional programming techniques in regular JavaScript
Functional programming techniques in regular JavaScriptFunctional programming techniques in regular JavaScript
Functional programming techniques in regular JavaScriptPavel Klimiankou
 
[FT-11][ltchen] A Tale of Two Monads
[FT-11][ltchen] A Tale of Two Monads[FT-11][ltchen] A Tale of Two Monads
[FT-11][ltchen] A Tale of Two MonadsFunctional Thursday
 
Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production DebuggingTakipi
 
Project Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaProject Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaC4Media
 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Monica Beckwith
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were PossibleLukas Eder
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureKelly Goetsch
 

Destacado (15)

Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Monad as things to do
Monad as things to doMonad as things to do
Monad as things to do
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8
 
Monads in practice
Monads in practiceMonads in practice
Monads in practice
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Category Theory for Mortal Programmers
Category Theory for Mortal ProgrammersCategory Theory for Mortal Programmers
Category Theory for Mortal Programmers
 
Functional programming techniques in regular JavaScript
Functional programming techniques in regular JavaScriptFunctional programming techniques in regular JavaScript
Functional programming techniques in regular JavaScript
 
[FT-11][ltchen] A Tale of Two Monads
[FT-11][ltchen] A Tale of Two Monads[FT-11][ltchen] A Tale of Two Monads
[FT-11][ltchen] A Tale of Two Monads
 
Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production Debugging
 
Project Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaProject Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To Java
 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!
 
In Search of Segmentation
In Search of SegmentationIn Search of Segmentation
In Search of Segmentation
 
10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible10 SQL Tricks that You Didn't Think Were Possible
10 SQL Tricks that You Didn't Think Were Possible
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright Future
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 

Similar a Monads

Category Theory made easy with (ugly) pictures
Category Theory made easy with (ugly) picturesCategory Theory made easy with (ugly) pictures
Category Theory made easy with (ugly) picturesAshwin Rao
 
Seismic data processing lecture 3
Seismic data processing lecture 3Seismic data processing lecture 3
Seismic data processing lecture 3Amin khalil
 
Reduction Monads and Their Signatures
Reduction Monads and Their SignaturesReduction Monads and Their Signatures
Reduction Monads and Their SignaturesMarco Maggesi
 
Lambda Calculus & Functional programming
Lambda Calculus & Functional programmingLambda Calculus & Functional programming
Lambda Calculus & Functional programmingAlexander Nemish
 
Lesson 2: A Catalog of Essential Functions
Lesson 2: A Catalog of Essential FunctionsLesson 2: A Catalog of Essential Functions
Lesson 2: A Catalog of Essential FunctionsMatthew Leingang
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfjannatulferdousmaish
 
Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...
Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...
Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...MLconf
 
Subgradient Methods for Huge-Scale Optimization Problems - Юрий Нестеров, Cat...
Subgradient Methods for Huge-Scale Optimization Problems - Юрий Нестеров, Cat...Subgradient Methods for Huge-Scale Optimization Problems - Юрий Нестеров, Cat...
Subgradient Methods for Huge-Scale Optimization Problems - Юрий Нестеров, Cat...Yandex
 
Linear Algebra Presentation including basic of linear Algebra
Linear Algebra Presentation including basic of linear AlgebraLinear Algebra Presentation including basic of linear Algebra
Linear Algebra Presentation including basic of linear AlgebraMUHAMMADUSMAN93058
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkreddyprasad reddyvari
 
DSP2_slides_04_adaptievefiltering.pdf
DSP2_slides_04_adaptievefiltering.pdfDSP2_slides_04_adaptievefiltering.pdf
DSP2_slides_04_adaptievefiltering.pdfRakuoane
 
Programming with effects - Graham Hutton
Programming with effects - Graham HuttonProgramming with effects - Graham Hutton
Programming with effects - Graham HuttonWen-Shih Chao
 
Data Analysis and Algorithms Lecture 1: Introduction
 Data Analysis and Algorithms Lecture 1: Introduction Data Analysis and Algorithms Lecture 1: Introduction
Data Analysis and Algorithms Lecture 1: IntroductionTayyabSattar5
 
Math major 14 differential calculus pw
Math major 14 differential calculus pwMath major 14 differential calculus pw
Math major 14 differential calculus pwReymart Bargamento
 

Similar a Monads (20)

Comonads in Haskell
Comonads in HaskellComonads in Haskell
Comonads in Haskell
 
Category Theory made easy with (ugly) pictures
Category Theory made easy with (ugly) picturesCategory Theory made easy with (ugly) pictures
Category Theory made easy with (ugly) pictures
 
Seismic data processing lecture 3
Seismic data processing lecture 3Seismic data processing lecture 3
Seismic data processing lecture 3
 
Reduction Monads and Their Signatures
Reduction Monads and Their SignaturesReduction Monads and Their Signatures
Reduction Monads and Their Signatures
 
Lambda Calculus & Functional programming
Lambda Calculus & Functional programmingLambda Calculus & Functional programming
Lambda Calculus & Functional programming
 
Lesson 2: A Catalog of Essential Functions
Lesson 2: A Catalog of Essential FunctionsLesson 2: A Catalog of Essential Functions
Lesson 2: A Catalog of Essential Functions
 
Computer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdfComputer algorithm(Dynamic Programming).pdf
Computer algorithm(Dynamic Programming).pdf
 
bv_cvxslides (1).pdf
bv_cvxslides (1).pdfbv_cvxslides (1).pdf
bv_cvxslides (1).pdf
 
Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...
Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...
Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...
 
Subgradient Methods for Huge-Scale Optimization Problems - Юрий Нестеров, Cat...
Subgradient Methods for Huge-Scale Optimization Problems - Юрий Нестеров, Cat...Subgradient Methods for Huge-Scale Optimization Problems - Юрий Нестеров, Cat...
Subgradient Methods for Huge-Scale Optimization Problems - Юрий Нестеров, Cat...
 
Linear Algebra Presentation including basic of linear Algebra
Linear Algebra Presentation including basic of linear AlgebraLinear Algebra Presentation including basic of linear Algebra
Linear Algebra Presentation including basic of linear Algebra
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
 
DSP2_slides_04_adaptievefiltering.pdf
DSP2_slides_04_adaptievefiltering.pdfDSP2_slides_04_adaptievefiltering.pdf
DSP2_slides_04_adaptievefiltering.pdf
 
introduction to matlab.pptx
introduction to matlab.pptxintroduction to matlab.pptx
introduction to matlab.pptx
 
Programming with effects - Graham Hutton
Programming with effects - Graham HuttonProgramming with effects - Graham Hutton
Programming with effects - Graham Hutton
 
Data Analysis and Algorithms Lecture 1: Introduction
 Data Analysis and Algorithms Lecture 1: Introduction Data Analysis and Algorithms Lecture 1: Introduction
Data Analysis and Algorithms Lecture 1: Introduction
 
A bit about мcmc
A bit about мcmcA bit about мcmc
A bit about мcmc
 
Presentation gauge field theory
Presentation gauge field theoryPresentation gauge field theory
Presentation gauge field theory
 
Math major 14 differential calculus pw
Math major 14 differential calculus pwMath major 14 differential calculus pw
Math major 14 differential calculus pw
 
Hyper loglog
Hyper loglogHyper loglog
Hyper loglog
 

Monads

  • 1. A Tale of Two Monads: Category-theoretic and Computational viewpoints Liang-Ting Chen
  • 2. What is … a monad? Functional Programmer:
  • 3. What is … a monad? Functional Programmer: • a warm, fuzzy, little thing Monica Monad, by FalconNL
  • 4. What is … a monad? Functional Programmer: • a warm, fuzzy, little thing • return and bind with monad laws class Monad m where (>>=) ::m a->(a -> m b)->m b return::a ->m a ! -- monad laws return a >>= k = k a m >>= return = m m >>= (x-> k x >>= h) =
 (m >>= k) >>= h
  • 5. • • What is … a monad? Functional Programmer: • a warm, fuzzy, little thing • return and bind with monad laws • a programmable semicolon do { x' <- return x; f x’} 
 ≡ do { f x }
 do { x <- m; return x }
 ≡ do { m }
 • do { y <- do { x <- m; f x } g y }
 ≡ do { x <- m; do { y <- f x; g y }}
 ≡ do { x <- m; y <- f x; g y }
  • 6. Kleisli Triple T : Obj(C) ! Obj(C) ⌘A : A ! T A ⇤ ( ) : hom(A, T B) ! hom(T A, T B) What is … a monad? Functional Programmer: • a warm, fuzzy, little thing • return and bind with monad laws • a programmable semicolon • E. Moggi, “Notions of computation and monads”, 1991 `M : (return) ` [M ]T : T ` M : T⌧ x:⌧ `N :T (bind) ` letT (x ( M ) in N : T monad laws ⇤ ⌘A ⇤ = id T A ⌘A ; f = f ⇤ ⇤ ⇤ f ; g = (f ; g)
  • 7. “Hey, mathematician! What is a monad?”,
 you asked.
  • 8. “A monad in X is just a monoid in the category of endofunctors of X, what’s the problem?” –Philip Wadler
  • 9. “A monad in X is just a monoid in the category of endofunctors of X, what’s the problem?” –James Iry, A Brief, Incomplete and Mostly Wrong History of Programming Languages
  • 10. “A monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.” –Saunders Mac Lane, Categories for the Working Mathematician, p.138
  • 11. monad on a category What is … a monad? Mathematician: • a monoid in the category of endofunctors T: C !C ⌘ : I !T ˙ µ : T 2 !T ˙ monad laws T 3 Tµ / T2 µ µT ✏ T2 T T⌘ µ ✏ /T 2 /T o ⌘T µ id ✏ ~ T id T
  • 12. monad in a bicategory • 0-cell a; What is … a monad? Mathematician: • a monoid in the category of endofunctors • a monoid in the endomorphism category K(a,a) of a bicategory K • 1-cell t : a ! a; • 2-cell ⌘ : 1a ! t, and µ : tt ! t monad laws ttt tµ / tt t µ µt ✏ tt µ ✏ /t t⌘ / tt o ⌘t µ id ✏  t id t
  • 13. What is … a monad? Mathematician: • a monoid in the category of endofunctors • a monoid in the endomorphism category K(a,a) of a bicategory K • … from Su Horng’s slide
  • 14. Monads in Haskell, the Abstract Ones • class Functor m => Monad m where
 unit :: a -> m a -- η 
 join :: m (m a) -> m a -- μ • --join . (fmap join) = join . join
 --join . (fmap unit) = join . unit = id T 3 Tµ /T 2 µ µT ✏ T2 µ ✏ /T T T⌘ 2 /T o ⌘T µ id ✏ ~ T id T
  • 15. Kleisli Triples and Monads are Equivalent (Manes 1976) fmap :: Monad m => (a -> b) -> m a -> m b
 fmap f x = x >>= return . f
 • 
 join :: Monad m => m (m a) -> m a
 join x = x >>= id
 -- id :: m a -> m a
  • 16. Kleisli Triples and Monads are Equivalent (Manes 1976) fmap :: Monad m => (a -> b) -> m a -> m b
 fmap f x = x >>= return . f
 • 
 join :: Monad m => m (m a) -> m a
 join x = x >>= id
 -- id :: m a -> m a • (>>=) :: Monad m => m a -> (a -> m b) -> m b
 x >>= f = join (fmap f x)
 -- fmap f :: m a -> m (m b)
  • 17. Monads are derivable from algebraic operations and equations if and only if they have finite rank. –G. M. Kelly and A. J. Power, Adjunctions whose counits are coequalizers, and presentations of finitary enriched monads, 1993.
  • 18. An Algebraic Theory: Monoid • a set M with • a nullary operation ✏ : 1 ! M • a binary operation • : M ⇥ M ! M satisfying • associativity: (a • b) • c = a • (b • c) • identity: a • ✏ = ✏ • a = a
  • 19. Monoids in Haskell: class Monoid a where mempty :: a -- ^ Identity of 'mappend' mappend :: a -> a -> a -- ^ An associative operation ! instance Monoid [a] where mempty = [] mappend = (++) ! instance Monoid b => Monoid (a -> b) where mempty _ = mempty mappend f g x = f x `mappend` g x
  • 20. An Algebraic Theory: Semi-lattice • a set L with • a binary operation _ : M ⇥ M ! M satisfying • commutativity: a _ b = b _ a • associativity: a _ (b _ c) = (a _ b) _ c • idenpotency: a _ a = a
  • 21. Semi-lattices in Haskell class SemiLattice a where join :: a -> a -> a ! instance SemiLattice Bool where join = (||) ! instance SemiLattice v => SemiLattice (k -> v) where f `join` g = x -> f x `join` g x ! instance SemiLattice IntSet where join = union
  • 22. An Algebraic Theory (defined as a type class in Haskell) • a set of operations 2 ⌃ and ar( ) 2 N • a set of equations with variables, e.g. 1 ( 1 (x, y), z) = 1 (x, 1 (y, z))
  • 23. A Model of an Algebraic Theory (an instance) • a set M with • an n-ary function M for each operation satisfying each equation with ar( ) = n
  • 24. A Monad with Finite Rank MX = [ { M i[M S] | i : S ✓f X } (M i : M S ! M X)
  • 25. Examples of Algebraic Effects • maybe X 7! X + 1 • exceptions X 7! X + E • nondeterminism X 7! Pfin (X) • side-effects X 7! (X ⇥ State) State but continuations is not algebraic X 7! R (RX )
  • 26. Algebraic Theory of Exception • nullary operations raisee for each e 2 E • no equations A monadic program f :: A -> B + E corresponds to a homomorphism between free algebras
  • 27. Why Algebraic Effects? • Various ways of combination, e.g. sum, product, distribution, etc. • Equational reasoning of monadic programming is simpler. • A classification of effects: a deeper insight.
  • 28. Conclusion • Moggi’s formulation solves fundamental problems, e.g. a unified approach to I/O. • Mathematicians bring new ideas to functional programming, e.g. algebraic effects, modular construction of effects • Still an ongoing area
  • 29. Conclusion • Moggi’s formulation solves fundamental problems, e.g. a unified approach to I/O. • Mathematicians bring new ideas to functional programming, e.g. algebraic effects, modular construction of effects • Still an ongoing area