SlideShare a Scribd company logo
1 of 19
Download to read offline
Humble introduction to
category theory in Haskell
September 29, 2015
leejongsoo@gmail.com
Haskell
● A standardized, general-purpose purely functional programming language,
with non-strict semantics and strong static typing.
● It is named after logician Haskell Curry.
● Elegant! Expressive! Fast! But, ...
I’m here !
Category Theory
Category
- A collection of objects
- A collection of morphism from one to another object
- Composition, a binary operation defined on compatible pairs of morphisms
- Require Associativity and Identity
Functor
A type of mapping between categories
class Functor f where
fmap :: (a -> b) -> f a -> f b
Functor in Haskell
Any type that takes one concrete type to produce a concrete type
- Maybe
- Tree
- Either
instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap f Nothing = Nothing
instance Functor Tree where
fmap f EmptyTree = EmptyTree
fmap f (Node x left right) = Node (f x) (fmap f left) (fmap f right)
instance Functor Either a where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
‘Either a’, not ‘Either’. Why???
(b -> c) -> Either a b -> Either a c
(b -> c) -> (Either a) b -> (Either a) c
(b -> c) -> f b -> f c
How about function?
chr :: Int -> Char ord :: Char -> Int
Change to prefix form from infix form
chr :: (-> Int) Char ord :: (-> Char) Int
Function is a first-class citizen, not special.
(b -> c) -> (a -> b) -> ( a -> c)
(b -> c) -> (-> a) b -> (-> a) c
(b -> c) -> f b -> f c
instance Functor ((->) r) where
fmap = (.)
instance Functor IO where
fmap f action = do
result <- action
return (f result)
Functor and Currying
Currying is the process of transforming a function that takes multiple arguments
into a function that takes just a single argument and returns another function if any
arguments are still needed.
add :: Int -> Int -> Int add :: Int -> (Int -> Int)
add a b = a + b add a = b -> a + b
Functor should take one concrete type.
In Haskell, all function take one concrete type because of currying!
Functor Laws
Law 1
fmap id == id
Law 2
fmap (f . g) == fmap f . fmap g
== fmap f (fmap g x)
Lift?
● Takes a function and a functor values and then maps that function over the
functor value
fmap :: (a -> b) -> f a -> f b
● Takes a function and lifts that function so it operates on functor values
fmap :: (a -> b) -> (f a -> f b)
Applicative Functor
A pattern that popped up time and again in our daily work, effectual programming
in Haskell.[1]
● More instance and sufficient for many uses like context-free parsing
● instances can perform analysis of computations before they are executed,
and thus produce shared optimizations.
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
With Applicative type class, we can chain the use of the <*> function, thus
enabling us to seamlessly operate on several applicative values instead of just
one. [1] Functional pearl - Applicative programming with effects
Applicative Functors (1)
Maybe
instance Applicative May be where
pure = just
Nothing <*> _ = Nothing
(Just f) <*> x = fmap f x
List
instance Applicative [] where
pure x = [x]
fs <*> xs = [f x | f <- fs, x <- xs]
Applicative Style
pure (+) <*> Just 3 <*> Just 5 (pure (+) <*> Just 3) <*> Just 5
Isn’t this awesome?
Applicative functors and the applicative style of pure f <*> x <*> y <*> … allow us to
take a function that expects parameters that aren’t applicative values and use that
function to operate on several applicative values.
(<$>) :: (Functor f) => (a -> b) -> f a -> f b
f <$> x = pure f <*> x -- (1)
f <$> x = fmap f x -- (2) (1)is same with (2).
Applicative Functors (2)
IO
instance Applicative IO be where
pure = return
a <*> b = do f <- a
x <- b
return (f x)
Function
instance Applicative ((->) r) where
pure x = (_ -> x)
f <*> g = x -> f x (g x)
Example
(pure 3) “blah” == 3
(+) <$> (+3) <*> (*100) $ 5 == 508
(x y z -> [x,y,z]) <$> (+3) <*> (*2) <*>
(/2) $ 5 == [8.0,10.0,2.5]
Applicative Laws
Law 1
pure id <*> v = v
Law 2
pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
Law 3
pure f <*> pure x = pure (f x)
Law 4
u <*> pure y = pure ($ y) <*> u
Monoid
In category theory, a monoid (or monoid object) (M, μ, η) in a monoidal category
(C, ⊗, I) is an object M together with two morphisms. It has a associativity binary
operator and identity element.
- μ: M ⊗ M → M called multiplication,
- η: I → M called unit,
class Monoid m where -- only concrete types can be made instances of Monoid
mempty :: m
mappend :: m -> m -> m
mconcat :: [m] -> m
mconcat = foldr mappend mempty
Monad
Monads are a natural extension of applicative functors.
If we have a value with a context, ‘m a’, how do we apply to it a function that takes
a ‘normal a’ and returns a ‘value with a context’?
Many common programming concepts can be described in terms of a monad
structure, including side effects such as input/output, variable assignment,
exception handling, parsing, nondeterminism, concurrency, and continuations.
Simply, Monads are programmable semicolons in the Haskell.
The Monad Type Class
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
x >> y = x >>= _ -> y
Example of Monad
/* Java */
String s = System.console().
readLine();
int n = Integer.parseInt(s);
n = n + 3
System.out.printf(“result:”);
System.out.printf(“%d”, n);
do Notation (Syntatic sugar!)
do s <- getLine
let n = read s :: Int
let n2 = n + 3
putStr “result: “
putStrLn $ show n2
getLine
>>= s -> let n = read s :: Int
n2 = n + 3
in putStr “result: “
>>= _ -> putStrLn $ show n2
Conclusion
Don’t concentrate on category theory itself.
Long time ago, old functional programmers found some patterns in their codes.
They want to generalize the found patterns and want to get an elegant abstraction.
But good abstraction is not a easy work. Some of them are also great
mathematician. They borrowed the concepts from mathematics like category
theory.
Don’t reinvent the wheel. Just use the wheel.
Of course, if you know why and how they made wheel, it’s very helpful to you.
Reference
● http://learnyouahaskell.com
● https://wiki.haskell.org/Haskell
● https://wikipedia.org
● https://namu.wiki

More Related Content

What's hot

Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!John De Goes
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedSusan Potter
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slidesOCaml
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...John De Goes
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1Hackraft
 
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
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadOliver Daff
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskellLuca Molteni
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 

What's hot (20)

Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Zippers
ZippersZippers
Zippers
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
MTL Versus Free
MTL Versus FreeMTL Versus Free
MTL Versus Free
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
 
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
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
 
Functor, Apply, Applicative And Monad
Functor, Apply, Applicative And MonadFunctor, Apply, Applicative And Monad
Functor, Apply, Applicative And Monad
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskell
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 

Similar to Humble introduction to category theory in haskell

Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit partsMaxim Zaks
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Functional programming from its fundamentals
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentalsMauro Palsgraaf
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursionDavid Atchley
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
 

Similar to Humble introduction to category theory in haskell (20)

10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
Practical cats
Practical catsPractical cats
Practical cats
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Functional programming from its fundamentals
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentals
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
functions
functionsfunctions
functions
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
 

Recently uploaded

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Recently uploaded (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Humble introduction to category theory in haskell

  • 1. Humble introduction to category theory in Haskell September 29, 2015 leejongsoo@gmail.com
  • 2. Haskell ● A standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. ● It is named after logician Haskell Curry. ● Elegant! Expressive! Fast! But, ... I’m here !
  • 3. Category Theory Category - A collection of objects - A collection of morphism from one to another object - Composition, a binary operation defined on compatible pairs of morphisms - Require Associativity and Identity Functor A type of mapping between categories class Functor f where fmap :: (a -> b) -> f a -> f b
  • 4. Functor in Haskell Any type that takes one concrete type to produce a concrete type - Maybe - Tree - Either instance Functor Maybe where fmap f (Just x) = Just (f x) fmap f Nothing = Nothing instance Functor Tree where fmap f EmptyTree = EmptyTree fmap f (Node x left right) = Node (f x) (fmap f left) (fmap f right) instance Functor Either a where fmap f (Right x) = Right (f x) fmap f (Left x) = Left x ‘Either a’, not ‘Either’. Why??? (b -> c) -> Either a b -> Either a c (b -> c) -> (Either a) b -> (Either a) c (b -> c) -> f b -> f c
  • 5. How about function? chr :: Int -> Char ord :: Char -> Int Change to prefix form from infix form chr :: (-> Int) Char ord :: (-> Char) Int Function is a first-class citizen, not special. (b -> c) -> (a -> b) -> ( a -> c) (b -> c) -> (-> a) b -> (-> a) c (b -> c) -> f b -> f c instance Functor ((->) r) where fmap = (.) instance Functor IO where fmap f action = do result <- action return (f result)
  • 6. Functor and Currying Currying is the process of transforming a function that takes multiple arguments into a function that takes just a single argument and returns another function if any arguments are still needed. add :: Int -> Int -> Int add :: Int -> (Int -> Int) add a b = a + b add a = b -> a + b Functor should take one concrete type. In Haskell, all function take one concrete type because of currying!
  • 7. Functor Laws Law 1 fmap id == id Law 2 fmap (f . g) == fmap f . fmap g == fmap f (fmap g x)
  • 8. Lift? ● Takes a function and a functor values and then maps that function over the functor value fmap :: (a -> b) -> f a -> f b ● Takes a function and lifts that function so it operates on functor values fmap :: (a -> b) -> (f a -> f b)
  • 9. Applicative Functor A pattern that popped up time and again in our daily work, effectual programming in Haskell.[1] ● More instance and sufficient for many uses like context-free parsing ● instances can perform analysis of computations before they are executed, and thus produce shared optimizations. class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b With Applicative type class, we can chain the use of the <*> function, thus enabling us to seamlessly operate on several applicative values instead of just one. [1] Functional pearl - Applicative programming with effects
  • 10. Applicative Functors (1) Maybe instance Applicative May be where pure = just Nothing <*> _ = Nothing (Just f) <*> x = fmap f x List instance Applicative [] where pure x = [x] fs <*> xs = [f x | f <- fs, x <- xs]
  • 11. Applicative Style pure (+) <*> Just 3 <*> Just 5 (pure (+) <*> Just 3) <*> Just 5 Isn’t this awesome? Applicative functors and the applicative style of pure f <*> x <*> y <*> … allow us to take a function that expects parameters that aren’t applicative values and use that function to operate on several applicative values. (<$>) :: (Functor f) => (a -> b) -> f a -> f b f <$> x = pure f <*> x -- (1) f <$> x = fmap f x -- (2) (1)is same with (2).
  • 12. Applicative Functors (2) IO instance Applicative IO be where pure = return a <*> b = do f <- a x <- b return (f x) Function instance Applicative ((->) r) where pure x = (_ -> x) f <*> g = x -> f x (g x) Example (pure 3) “blah” == 3 (+) <$> (+3) <*> (*100) $ 5 == 508 (x y z -> [x,y,z]) <$> (+3) <*> (*2) <*> (/2) $ 5 == [8.0,10.0,2.5]
  • 13. Applicative Laws Law 1 pure id <*> v = v Law 2 pure (.) <*> u <*> v <*> w = u <*> (v <*> w) Law 3 pure f <*> pure x = pure (f x) Law 4 u <*> pure y = pure ($ y) <*> u
  • 14. Monoid In category theory, a monoid (or monoid object) (M, μ, η) in a monoidal category (C, ⊗, I) is an object M together with two morphisms. It has a associativity binary operator and identity element. - μ: M ⊗ M → M called multiplication, - η: I → M called unit, class Monoid m where -- only concrete types can be made instances of Monoid mempty :: m mappend :: m -> m -> m mconcat :: [m] -> m mconcat = foldr mappend mempty
  • 15. Monad Monads are a natural extension of applicative functors. If we have a value with a context, ‘m a’, how do we apply to it a function that takes a ‘normal a’ and returns a ‘value with a context’? Many common programming concepts can be described in terms of a monad structure, including side effects such as input/output, variable assignment, exception handling, parsing, nondeterminism, concurrency, and continuations. Simply, Monads are programmable semicolons in the Haskell.
  • 16. The Monad Type Class class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b x >> y = x >>= _ -> y
  • 17. Example of Monad /* Java */ String s = System.console(). readLine(); int n = Integer.parseInt(s); n = n + 3 System.out.printf(“result:”); System.out.printf(“%d”, n); do Notation (Syntatic sugar!) do s <- getLine let n = read s :: Int let n2 = n + 3 putStr “result: “ putStrLn $ show n2 getLine >>= s -> let n = read s :: Int n2 = n + 3 in putStr “result: “ >>= _ -> putStrLn $ show n2
  • 18. Conclusion Don’t concentrate on category theory itself. Long time ago, old functional programmers found some patterns in their codes. They want to generalize the found patterns and want to get an elegant abstraction. But good abstraction is not a easy work. Some of them are also great mathematician. They borrowed the concepts from mathematics like category theory. Don’t reinvent the wheel. Just use the wheel. Of course, if you know why and how they made wheel, it’s very helpful to you.