SlideShare a Scribd company logo
1 of 80
Download to read offline
An Invitation to Functional Programming
Sonat S¨uer
Picus Security
February 14 2018
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 1 / 25
Overview
1 Shameless Promotion
2 Functional programming
3 A Toy Example in Detail
4 Sketch of a Vast Generalization
5 Another Example
6 Final Remarks
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 2 / 25
Shameless Promotion
Let us cut to the chase...
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 3 / 25
Shameless Promotion
Let us cut to the chase...
My company, Picus Security, is on a hunt for talent and I am here to lure
you into software engineering and functional programming.
If you decide you are interested after the talk, contact me:
sonat@picussecurity.com.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 3 / 25
What is functional programming?
Here is the definition on Wikipedia:
In computer science, functional programming is a programming
paradigm that treats computation as the evaluation of
mathematical functions and avoids changing-state and mutable
data.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 4 / 25
What is functional programming?
Here is the definition on Wikipedia:
In computer science, functional programming is a programming
paradigm that treats computation as the evaluation of
mathematical functions and avoids changing-state and mutable
data.
This should be familiar to programmers. . .
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 4 / 25
What is functional programming?
Here is the definition on Wikipedia:
In computer science, functional programming is a programming
paradigm that treats computation as the evaluation of
mathematical functions and avoids changing-state and mutable
data.
This should be familiar to programmers. . .
. . . and very appealing to mathematicians.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 4 / 25
Why should it be appealing to mathematicians?
Because choosing pure –i.e. mathematical– functions as a foundation
means that programs are algebraic objects. Computation is literally
simplification of algebraic expressions.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 5 / 25
Why should it be appealing to mathematicians?
Because choosing pure –i.e. mathematical– functions as a foundation
means that programs are algebraic objects. Computation is literally
simplification of algebraic expressions.
This is very intuitive from the point of view of a mathematician. For
instance, we can use substituition of equals for equals principle as a way to
reason about programs.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 5 / 25
Why should it be appealing to mathematicians?
Because choosing pure –i.e. mathematical– functions as a foundation
means that programs are algebraic objects. Computation is literally
simplification of algebraic expressions.
This is very intuitive from the point of view of a mathematician. For
instance, we can use substituition of equals for equals principle as a way to
reason about programs.
This is also very useful from the point of view of a programmer. It even
has a name in computer science. It is called referential transparency.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 5 / 25
Why should it be appealing to mathematicians?
Because choosing pure –i.e. mathematical– functions as a foundation
means that programs are algebraic objects. Computation is literally
simplification of algebraic expressions.
This is very intuitive from the point of view of a mathematician. For
instance, we can use substituition of equals for equals principle as a way to
reason about programs.
This is also very useful from the point of view of a programmer. It even
has a name in computer science. It is called referential transparency.
Note that in imperative languages referential transparency fails.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 5 / 25
Enter Haskell
We will work out an example of the programs are algebraic objects
approach in detail. For that we will use Haskell, an industrial strength pure
functional language, named after the mathematician and logician Haskell
Curry.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 6 / 25
Enter Haskell
We will work out an example of the programs are algebraic objects
approach in detail. For that we will use Haskell, an industrial strength pure
functional language, named after the mathematician and logician Haskell
Curry.
This will not be a crash course in Haskell. Instead, I will explain the syntax
as we go. If you have any difficulty in reading a code snippet, please ask!
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 6 / 25
Lists in Haskell
Like the vast majority of programming languages, Haskell has data
structures. One of the most common data structures in Haskell is the list
structure.
Here is the definition: given a type a, (like integers, floating point
numbers, strings, etc.) we define [a] by structural recursion as follows:
1 [] is a list, it is called the empty list;
2 if x is an element of type a and xs is a list of elements of type a then
x : xs is also list.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 7 / 25
Lists in Haskell
Like the vast majority of programming languages, Haskell has data
structures. One of the most common data structures in Haskell is the list
structure.
Here is the definition: given a type a, (like integers, floating point
numbers, strings, etc.) we define [a] by structural recursion as follows:
1 [] is a list, it is called the empty list;
2 if x is an element of type a and xs is a list of elements of type a then
x : xs is also list.
For instance
1 : (2 : (3 : [])) = 1 : 2 : 3 : []
is a list of integers. Haskell allows us to express this list as [1, 2, 3].
Note that here : is a actually binary operation and a list actually a term.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 7 / 25
Concatenation
Now let us define a simple function on lists.
Let xs and ys be two lists (over the same type). We define the
concatenation xs + +ys of xs and ys by recursion on the structure of xs as
follows:
[] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys).
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
Concatenation
Now let us define a simple function on lists.
Let xs and ys be two lists (over the same type). We define the
concatenation xs + +ys of xs and ys by recursion on the structure of xs as
follows:
[] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys).
Let us compute an example:
[1, 2] + +[3, 4] =
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
Concatenation
Now let us define a simple function on lists.
Let xs and ys be two lists (over the same type). We define the
concatenation xs + +ys of xs and ys by recursion on the structure of xs as
follows:
[] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys).
Let us compute an example:
[1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : []))
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
Concatenation
Now let us define a simple function on lists.
Let xs and ys be two lists (over the same type). We define the
concatenation xs + +ys of xs and ys by recursion on the structure of xs as
follows:
[] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys).
Let us compute an example:
[1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : []))
=1 : ((2 : []) + +(3 : (4 : []))
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
Concatenation
Now let us define a simple function on lists.
Let xs and ys be two lists (over the same type). We define the
concatenation xs + +ys of xs and ys by recursion on the structure of xs as
follows:
[] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys).
Let us compute an example:
[1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : []))
=1 : ((2 : []) + +(3 : (4 : []))
=1 : (2 : ([] + +(3 : (4 : [])))
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
Concatenation
Now let us define a simple function on lists.
Let xs and ys be two lists (over the same type). We define the
concatenation xs + +ys of xs and ys by recursion on the structure of xs as
follows:
[] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys).
Let us compute an example:
[1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : []))
=1 : ((2 : []) + +(3 : (4 : []))
=1 : (2 : ([] + +(3 : (4 : [])))
=1 : (2 : (3 : (4 : [])))
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
Concatenation
Now let us define a simple function on lists.
Let xs and ys be two lists (over the same type). We define the
concatenation xs + +ys of xs and ys by recursion on the structure of xs as
follows:
[] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys).
Let us compute an example:
[1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : []))
=1 : ((2 : []) + +(3 : (4 : []))
=1 : (2 : ([] + +(3 : (4 : [])))
=1 : (2 : (3 : (4 : [])))
=[1, 2, 3, 4]
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
Naive reverse function
Suppose that we want to devise a function –that is to say, write a
program– which produces the reverse of a list.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 9 / 25
Naive reverse function
Suppose that we want to devise a function –that is to say, write a
program– which produces the reverse of a list.
Here is the obvious solution. Given a list xs let us define naiveReverse as
follows:
naiveReverse [] = [] and naiveReverse (x : xs) = naiveReverse xs++[x].
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 9 / 25
Naive reverse function
Suppose that we want to devise a function –that is to say, write a
program– which produces the reverse of a list.
Here is the obvious solution. Given a list xs let us define naiveReverse as
follows:
naiveReverse [] = [] and naiveReverse (x : xs) = naiveReverse xs++[x].
As an exercise show that naiveReverse [1, 2, 3] = [3, 2, 1].
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 9 / 25
Complexity of the naive reverse function
First, note that the computation of xs + +ys requires length of xs many
applications of : operation.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 10 / 25
Complexity of the naive reverse function
First, note that the computation of xs + +ys requires length of xs many
applications of : operation.
Claim: Computation of naiveReverse xs requires 1
2n(n − 1) applications of
the operation : where n is the length of xs.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 10 / 25
Complexity of the naive reverse function
First, note that the computation of xs + +ys requires length of xs many
applications of : operation.
Claim: Computation of naiveReverse xs requires 1
2n(n − 1) applications of
the operation : where n is the length of xs.
Proof. By induction on n. Base case is trivial. Suppose the statement
holds for n. Let xs be of length n. Then for any x we have
naiveReverse (x : xs) = naiveReverse xs + +[x].
As naiveReverse xs and xs has the same length, namely n, computation of
++ takes n applications of the : operation. On the other hand, by
induction hypothesis, naiveReverse xs requires 1
2n(n − 1) applications.
Adding these two yields 1
2n(n + 1), which is what we want. QED
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 10 / 25
Complexity of the naive reverse function
First, note that the computation of xs + +ys requires length of xs many
applications of : operation.
Claim: Computation of naiveReverse xs requires 1
2n(n − 1) applications of
the operation : where n is the length of xs.
Proof. By induction on n. Base case is trivial. Suppose the statement
holds for n. Let xs be of length n. Then for any x we have
naiveReverse (x : xs) = naiveReverse xs + +[x].
As naiveReverse xs and xs has the same length, namely n, computation of
++ takes n applications of the : operation. On the other hand, by
induction hypothesis, naiveReverse xs requires 1
2n(n − 1) applications.
Adding these two yields 1
2n(n + 1), which is what we want. QED
So the complexity is quadratic as a function of the input length.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 10 / 25
The Basic Idea
The naive implementation of the reverse function is quadratic because ++
is expensive.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 11 / 25
The Basic Idea
The naive implementation of the reverse function is quadratic because ++
is expensive.
There is a very similar situation in mathematics with an elegant solution:
multiplication is expensive, however one can use logarithms to turn
multiplication into addition, do the additon and come back with
exponentiaiton.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 11 / 25
The Basic Idea
The naive implementation of the reverse function is quadratic because ++
is expensive.
There is a very similar situation in mathematics with an elegant solution:
multiplication is expensive, however one can use logarithms to turn
multiplication into addition, do the additon and come back with
exponentiaiton.
We will use the same trick, namely we will change the algebraic structure
we work in by using homomorphisms.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 11 / 25
A Small Remark Before We Continue
It is about to get technical. Without a certain background in mathematics
some of the things I will talk about may not make much sense.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 12 / 25
A Small Remark Before We Continue
It is about to get technical. Without a certain background in mathematics
some of the things I will talk about may not make much sense.
However, you should not leave the room because
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 12 / 25
A Small Remark Before We Continue
It is about to get technical. Without a certain background in mathematics
some of the things I will talk about may not make much sense.
However, you should not leave the room because
I will give an example for programmers, which will probably be
opaque for most mathematicians,
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 12 / 25
A Small Remark Before We Continue
It is about to get technical. Without a certain background in mathematics
some of the things I will talk about may not make much sense.
However, you should not leave the room because
I will give an example for programmers, which will probably be
opaque for most mathematicians,
You do not need to understand any of the mathematics here to be
productive in Haskell, or any other functional programming language.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 12 / 25
Algebra refresher: Cayley representation theorem
Recall that a monoid is a triple (M, ∗, e) where ∗ is a binary associative
operation on M and e is the identity element of ∗.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 13 / 25
Algebra refresher: Cayley representation theorem
Recall that a monoid is a triple (M, ∗, e) where ∗ is a binary associative
operation on M and e is the identity element of ∗.
Here are two important examples:
1 For any set S, the set of self maps of S, denoted by End(S) is a
monoid under composition. The identity is the identity function.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 13 / 25
Algebra refresher: Cayley representation theorem
Recall that a monoid is a triple (M, ∗, e) where ∗ is a binary associative
operation on M and e is the identity element of ∗.
Here are two important examples:
1 For any set S, the set of self maps of S, denoted by End(S) is a
monoid under composition. The identity is the identity function.
2 For any set S, the set of finite sequences with elements from S form a
monoid under concatenation. The identity is the empty list. (Actually
this is called the free monoid generated by S.)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 13 / 25
Algebra refresher: Cayley representation theorem
Theorem
Cayley A monoid with underlying set S can be embedded in End(S).
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 14 / 25
Algebra refresher: Cayley representation theorem
Theorem
Cayley A monoid with underlying set S can be embedded in End(S).
Proof.
One can easily check that C(s) = λs where λs(x) = s ∗ x is such an
embedding.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 14 / 25
Algebra refresher: Cayley representation theorem
Theorem
Cayley A monoid with underlying set S can be embedded in End(S).
Proof.
One can easily check that C(s) = λs where λs(x) = s ∗ x is such an
embedding.
Note that if a function f is in the image of C then one can recover the
element it came from by applying f to the identity of the monoid.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 14 / 25
Pushing the problem to End([a])
In End([a]), the monoidal operation, namely function composition, is very
cheap. To be more precise, it requires constant time because the
composition of two functions is left untouched untill someone tries to
apply it to a value.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 15 / 25
Pushing the problem to End([a])
In End([a]), the monoidal operation, namely function composition, is very
cheap. To be more precise, it requires constant time because the
composition of two functions is left untouched untill someone tries to
apply it to a value.
However, the notion of reverting only makes sense in [a] and not in
End([a]). So we need to embed only the concatenation part of the
problem into End([a]).
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 15 / 25
Pushing the problem to End([a])
In End([a]), the monoidal operation, namely function composition, is very
cheap. To be more precise, it requires constant time because the
composition of two functions is left untouched untill someone tries to
apply it to a value.
However, the notion of reverting only makes sense in [a] and not in
End([a]). So we need to embed only the concatenation part of the
problem into End([a]).
The inverse of xs is given by f xs [] where f is defined by
f [] = id and f (x : xs) = f xs ◦ C([x]).
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 15 / 25
Haskell Implementation
type End s = s -> s
singleton :: a -> End [a]
singleton x = f where f y = x : y
cayleyReverse :: [a] -> End [a]
cayleyReverse [] = id
cayleyReverse (x : xs) = cayleyReverse xs . singleton x
naiveReverse :: [a] -> [a]
naiveReverse [] = []
naiveReverse (x : xs) = naiveReverse xs ++ [x]
betterReverse :: [a] -> [a]
betterReverse xs = cayleyReverse xs []
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 16 / 25
Monoid Objects in a Category
We will port our method to different domains using category theory.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
Monoid Objects in a Category
We will port our method to different domains using category theory.
First, we need to translate our notions to category theory. Effectively, this
means expressing everything in terms of functions and their compositions.
We need
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
Monoid Objects in a Category
We will port our method to different domains using category theory.
First, we need to translate our notions to category theory. Effectively, this
means expressing everything in terms of functions and their compositions.
We need
Elements (using terminal objects)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
Monoid Objects in a Category
We will port our method to different domains using category theory.
First, we need to translate our notions to category theory. Effectively, this
means expressing everything in terms of functions and their compositions.
We need
Elements (using terminal objects)
Products (expressing Cartesian product as a categorical limit)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
Monoid Objects in a Category
We will port our method to different domains using category theory.
First, we need to translate our notions to category theory. Effectively, this
means expressing everything in terms of functions and their compositions.
We need
Elements (using terminal objects)
Products (expressing Cartesian product as a categorical limit)
Monoids (using the “associativity” of Cartesian products)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
Monoid Objects in a Category
We will port our method to different domains using category theory.
First, we need to translate our notions to category theory. Effectively, this
means expressing everything in terms of functions and their compositions.
We need
Elements (using terminal objects)
Products (expressing Cartesian product as a categorical limit)
Monoids (using the “associativity” of Cartesian products)
Now a monoid is a set M together with two functions ∗: M × M → M
and e : 1 → M satisfying the associativity and identitiy rules.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
Monoid Objects in a Category
We will port our method to different domains using category theory.
First, we need to translate our notions to category theory. Effectively, this
means expressing everything in terms of functions and their compositions.
We need
Elements (using terminal objects)
Products (expressing Cartesian product as a categorical limit)
Monoids (using the “associativity” of Cartesian products)
Now a monoid is a set M together with two functions ∗: M × M → M
and e : 1 → M satisfying the associativity and identitiy rules.
The associativity rule of a monoid M can be expressed by saying that the
two functions
∗ ◦ (id × ∗) and ∗ ◦ (∗ × id) ◦ α
from M × (M × M) to M are equal. (Here α(x, (y, z)) = ((x, y), z)).)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
Monoid Objects in a Category
We will port our method to different domains using category theory.
First, we need to translate our notions to category theory. Effectively, this
means expressing everything in terms of functions and their compositions.
We need
Elements (using terminal objects)
Products (expressing Cartesian product as a categorical limit)
Monoids (using the “associativity” of Cartesian products)
Now a monoid is a set M together with two functions ∗: M × M → M
and e : 1 → M satisfying the associativity and identitiy rules.
The associativity rule of a monoid M can be expressed by saying that the
two functions
∗ ◦ (id × ∗) and ∗ ◦ (∗ × id) ◦ α
from M × (M × M) to M are equal. (Here α(x, (y, z)) = ((x, y), z)).)
Exercise: Express the identity rule.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
Monoid Objects in a Monoidal Category
This is where the hand-waving starts. For actual definition you may use
Wikipedia.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 18 / 25
Monoid Objects in a Monoidal Category
This is where the hand-waving starts. For actual definition you may use
Wikipedia.
First, let us forget about sets and functions and work with an arbitrary
category. This means that we work with abstract objects and abstract
“maps” between them. The composition f ◦ g is defined only when the
codomain of g coincides with the domain of f . The only assumption
about this abstract composition is associativty.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 18 / 25
Monoid Objects in a Monoidal Category
This is where the hand-waving starts. For actual definition you may use
Wikipedia.
First, let us forget about sets and functions and work with an arbitrary
category. This means that we work with abstract objects and abstract
“maps” between them. The composition f ◦ g is defined only when the
codomain of g coincides with the domain of f . The only assumption
about this abstract composition is associativty.
Let us also forget about Cartesians product and work with an arbitrary
monoidal structure. This means that we have a binary construction on our
objects with a function like α –and a little bit more.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 18 / 25
Monoid Objects in a Monoidal Category
This is where the hand-waving starts. For actual definition you may use
Wikipedia.
First, let us forget about sets and functions and work with an arbitrary
category. This means that we work with abstract objects and abstract
“maps” between them. The composition f ◦ g is defined only when the
codomain of g coincides with the domain of f . The only assumption
about this abstract composition is associativty.
Let us also forget about Cartesians product and work with an arbitrary
monoidal structure. This means that we have a binary construction on our
objects with a function like α –and a little bit more.
It turns out that the notion of a monoid can be expressed in any category
with a monoidal structure. If your category is the category of sets and
functions between them and the monoidal structure is the Cartesian
product then you recover the original notion.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 18 / 25
Examples: Applicatives, Monads and Arrows
But is this generalization useful?
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
Examples: Applicatives, Monads and Arrows
But is this generalization useful? You bet! Here are some examples.
Let Hask be the category of types in Haskell with functions definable
in Haskell and pairing (or product) as the monoidal structure. (From
a strict point of view, this is not true but good enough to snatch ideas
from category theory.) Then for any a, [a] and End a are monoids.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
Examples: Applicatives, Monads and Arrows
But is this generalization useful? You bet! Here are some examples.
Let Hask be the category of types in Haskell with functions definable
in Haskell and pairing (or product) as the monoidal structure. (From
a strict point of view, this is not true but good enough to snatch ideas
from category theory.) Then for any a, [a] and End a are monoids.
Consider endofunctors of Hask with composition as the monoidal
structure. Then the monoids are called the monads. The Cayley
representation in this context is acalled the codensity monad
transformation for historical reasons.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
Examples: Applicatives, Monads and Arrows
But is this generalization useful? You bet! Here are some examples.
Let Hask be the category of types in Haskell with functions definable
in Haskell and pairing (or product) as the monoidal structure. (From
a strict point of view, this is not true but good enough to snatch ideas
from category theory.) Then for any a, [a] and End a are monoids.
Consider endofunctors of Hask with composition as the monoidal
structure. Then the monoids are called the monads. The Cayley
representation in this context is acalled the codensity monad
transformation for historical reasons.
In the category of endofunctors of Hask with Day convolution as the
monoidal structure the monoids are called the applicatives.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
Examples: Applicatives, Monads and Arrows
But is this generalization useful? You bet! Here are some examples.
Let Hask be the category of types in Haskell with functions definable
in Haskell and pairing (or product) as the monoidal structure. (From
a strict point of view, this is not true but good enough to snatch ideas
from category theory.) Then for any a, [a] and End a are monoids.
Consider endofunctors of Hask with composition as the monoidal
structure. Then the monoids are called the monads. The Cayley
representation in this context is acalled the codensity monad
transformation for historical reasons.
In the category of endofunctors of Hask with Day convolution as the
monoidal structure the monoids are called the applicatives.
In the category of profunctors with profunctor tensor as the monoidal
structure the monoids are called the weak arrows.
. . .
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
Tip of the iceberg
This was just one idea and its generalizations. Here is an incomplete list of
other relevant pure mathematical notions, each of which could be the
topic of a different talk:
Free constructions (free monads, free applicatives, etc.)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
Tip of the iceberg
This was just one idea and its generalizations. Here is an incomplete list of
other relevant pure mathematical notions, each of which could be the
topic of a different talk:
Free constructions (free monads, free applicatives, etc.)
Categorical duality (comonds, cofree constructions etc.)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
Tip of the iceberg
This was just one idea and its generalizations. Here is an incomplete list of
other relevant pure mathematical notions, each of which could be the
topic of a different talk:
Free constructions (free monads, free applicatives, etc.)
Categorical duality (comonds, cofree constructions etc.)
Functors (adjointness and representability)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
Tip of the iceberg
This was just one idea and its generalizations. Here is an incomplete list of
other relevant pure mathematical notions, each of which could be the
topic of a different talk:
Free constructions (free monads, free applicatives, etc.)
Categorical duality (comonds, cofree constructions etc.)
Functors (adjointness and representability)
Categories as databases (AQL and functorial migration)
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
Tip of the iceberg
This was just one idea and its generalizations. Here is an incomplete list of
other relevant pure mathematical notions, each of which could be the
topic of a different talk:
Free constructions (free monads, free applicatives, etc.)
Categorical duality (comonds, cofree constructions etc.)
Functors (adjointness and representability)
Categories as databases (AQL and functorial migration)
Curry-Howard correspondence
. . .
A lot of exciting things are happenning here!
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
The Example I Promised to Programmers
At this point, most programmers in the audience should be thinking “I’ve
been coding without knowing/understanding any of these abstract
mathematical concepts. Do I have to know/understand them?”
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 21 / 25
The Example I Promised to Programmers
At this point, most programmers in the audience should be thinking “I’ve
been coding without knowing/understanding any of these abstract
mathematical concepts. Do I have to know/understand them?”
The answer is no. This was mostly meant for mathematicians. One can
use these tools without understanding the theoretical background.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 21 / 25
The Example I Promised to Programmers
At this point, most programmers in the audience should be thinking “I’ve
been coding without knowing/understanding any of these abstract
mathematical concepts. Do I have to know/understand them?”
The answer is no. This was mostly meant for mathematicians. One can
use these tools without understanding the theoretical background.
However a certain shift in mentality seems to be unavoidable.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 21 / 25
The Example I Promised to Programmers
At this point, most programmers in the audience should be thinking “I’ve
been coding without knowing/understanding any of these abstract
mathematical concepts. Do I have to know/understand them?”
The answer is no. This was mostly meant for mathematicians. One can
use these tools without understanding the theoretical background.
However a certain shift in mentality seems to be unavoidable.
For that reason, I will give an example of what you can do with Haskell
from our own code base.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 21 / 25
Asynchronous Actions
Here is the problem: Suppose that we have some asynchronous actions
each of which can either return a value or fail with an error message. We
want to capture the first value returned by these actions. However, if they
all fail, we want to have a list of all the error messages returned. Optional:
The error messages should be ordered chronologically.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 22 / 25
Asynchronous Actions
Here is the problem: Suppose that we have some asynchronous actions
each of which can either return a value or fail with an error message. We
want to capture the first value returned by these actions. However, if they
all fail, we want to have a list of all the error messages returned. Optional:
The error messages should be ordered chronologically.
Please take a moment and try to solve this problem in your head using
your favourite language.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 22 / 25
Asynchronous Actions
Here is the problem: Suppose that we have some asynchronous actions
each of which can either return a value or fail with an error message. We
want to capture the first value returned by these actions. However, if they
all fail, we want to have a list of all the error messages returned. Optional:
The error messages should be ordered chronologically.
Please take a moment and try to solve this problem in your head using
your favourite language.
Our solution will depend on Async, a library developed by Simon Marlow.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 22 / 25
Haskell Implementation
pickFirstElligible
:: [Async (Either a b)]
-> IO (Either [a] b)
pickFirstElligible allActions =
run [] allActions ‘finally‘ mapM_ cancel allActions
where
run errs actions =
if null actions
then return $ Left $ reverse errs
else do (action, res) <- waitAny actions
case res of
Left err ->
run (err : errs) (delete action actions)
Right val ->
return $ Right val
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 23 / 25
Two mottos
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 24 / 25
Two mottos
There is nothing more practical than a good theory.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 24 / 25
Two mottos
There is nothing more practical than a good theory.
In theory, there is no difference between theory and practise. In
practise, there is.
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 24 / 25
Thank you for listening!
Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 25 / 25

More Related Content

What's hot

Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Meghaj Mallick
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
Preparation Data Structures 10 trees
Preparation Data Structures 10 treesPreparation Data Structures 10 trees
Preparation Data Structures 10 treesAndres Mendez-Vazquez
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structuresKuber Chandra
 
lecture 12
lecture 12lecture 12
lecture 12sajinsc
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treeszukun
 
Array Data Structures
Array Data StructuresArray Data Structures
Array Data StructuresSoni Gupta
 
Preparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_listPreparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_listAndres Mendez-Vazquez
 
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...Gianluca Amato
 
Lecture 5 data structures and algorithms
Lecture 5 data structures and algorithmsLecture 5 data structures and algorithms
Lecture 5 data structures and algorithmsAakash deep Singhal
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structureTushar Aneyrao
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine LearningAmanBhalla14
 
Review session2
Review session2Review session2
Review session2NEEDY12345
 

What's hot (20)

Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Preparation Data Structures 10 trees
Preparation Data Structures 10 treesPreparation Data Structures 10 trees
Preparation Data Structures 10 trees
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structures
 
lecture 12
lecture 12lecture 12
lecture 12
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure trees
 
Lec4
Lec4Lec4
Lec4
 
Chapter 11 ds
Chapter 11 dsChapter 11 ds
Chapter 11 ds
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
Array Data Structures
Array Data StructuresArray Data Structures
Array Data Structures
 
Preparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_listPreparation Data Structures 04 array linear_list
Preparation Data Structures 04 array linear_list
 
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
ICTCS 2015 - Exploiting linearity in sharing analysis of object-oriented prog...
 
Chapter 3 ds
Chapter 3 dsChapter 3 ds
Chapter 3 ds
 
Lecture 5 data structures and algorithms
Lecture 5 data structures and algorithmsLecture 5 data structures and algorithms
Lecture 5 data structures and algorithms
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine Learning
 
Review session2
Review session2Review session2
Review session2
 
Array
ArrayArray
Array
 

Similar to An Invitation to Functional Programming

III_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxIII_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxshashankbhadouria4
 
III_Data Structure_Module_1.ppt
III_Data Structure_Module_1.pptIII_Data Structure_Module_1.ppt
III_Data Structure_Module_1.pptshashankbhadouria4
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)Christopher Roach
 
SessionFour_DataTypesandObjects
SessionFour_DataTypesandObjectsSessionFour_DataTypesandObjects
SessionFour_DataTypesandObjectsHellen Gakuruh
 
Machine Learning Summer School 2016
Machine Learning Summer School 2016Machine Learning Summer School 2016
Machine Learning Summer School 2016chris wiggins
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data ManagementAlbert Bifet
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data CollectionJoseTanJr
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Languagevsssuresh
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
Types Working for You, Not Against You
Types Working for You, Not Against YouTypes Working for You, Not Against You
Types Working for You, Not Against YouC4Media
 
Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01shaziabibi5
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comShwetaAggarwal56
 

Similar to An Invitation to Functional Programming (20)

III_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxIII_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptx
 
III_Data Structure_Module_1.ppt
III_Data Structure_Module_1.pptIII_Data Structure_Module_1.ppt
III_Data Structure_Module_1.ppt
 
R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)R for Pythonistas (PyData NYC 2017)
R for Pythonistas (PyData NYC 2017)
 
R basics
R basicsR basics
R basics
 
SessionFour_DataTypesandObjects
SessionFour_DataTypesandObjectsSessionFour_DataTypesandObjects
SessionFour_DataTypesandObjects
 
Machine Learning Summer School 2016
Machine Learning Summer School 2016Machine Learning Summer School 2016
Machine Learning Summer School 2016
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data Collection
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 
An Intoduction to R
An Intoduction to RAn Intoduction to R
An Intoduction to R
 
Practical cats
Practical catsPractical cats
Practical cats
 
Have you met Julia?
Have you met Julia?Have you met Julia?
Have you met Julia?
 
Python for beginners
Python for beginnersPython for beginners
Python for beginners
 
Lecture_R.ppt
Lecture_R.pptLecture_R.ppt
Lecture_R.ppt
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
Types Working for You, Not Against You
Types Working for You, Not Against YouTypes Working for You, Not Against You
Types Working for You, Not Against You
 
CS151 Deep copy
CS151 Deep copyCS151 Deep copy
CS151 Deep copy
 
Data structures cs301 power point slides lecture 01
Data structures   cs301 power point slides lecture 01Data structures   cs301 power point slides lecture 01
Data structures cs301 power point slides lecture 01
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.com
 
R language introduction
R language introductionR language introduction
R language introduction
 

Recently uploaded

Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

An Invitation to Functional Programming

  • 1. An Invitation to Functional Programming Sonat S¨uer Picus Security February 14 2018 Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 1 / 25
  • 2. Overview 1 Shameless Promotion 2 Functional programming 3 A Toy Example in Detail 4 Sketch of a Vast Generalization 5 Another Example 6 Final Remarks Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 2 / 25
  • 3. Shameless Promotion Let us cut to the chase... Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 3 / 25
  • 4. Shameless Promotion Let us cut to the chase... My company, Picus Security, is on a hunt for talent and I am here to lure you into software engineering and functional programming. If you decide you are interested after the talk, contact me: sonat@picussecurity.com. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 3 / 25
  • 5. What is functional programming? Here is the definition on Wikipedia: In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 4 / 25
  • 6. What is functional programming? Here is the definition on Wikipedia: In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. This should be familiar to programmers. . . Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 4 / 25
  • 7. What is functional programming? Here is the definition on Wikipedia: In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. This should be familiar to programmers. . . . . . and very appealing to mathematicians. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 4 / 25
  • 8. Why should it be appealing to mathematicians? Because choosing pure –i.e. mathematical– functions as a foundation means that programs are algebraic objects. Computation is literally simplification of algebraic expressions. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 5 / 25
  • 9. Why should it be appealing to mathematicians? Because choosing pure –i.e. mathematical– functions as a foundation means that programs are algebraic objects. Computation is literally simplification of algebraic expressions. This is very intuitive from the point of view of a mathematician. For instance, we can use substituition of equals for equals principle as a way to reason about programs. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 5 / 25
  • 10. Why should it be appealing to mathematicians? Because choosing pure –i.e. mathematical– functions as a foundation means that programs are algebraic objects. Computation is literally simplification of algebraic expressions. This is very intuitive from the point of view of a mathematician. For instance, we can use substituition of equals for equals principle as a way to reason about programs. This is also very useful from the point of view of a programmer. It even has a name in computer science. It is called referential transparency. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 5 / 25
  • 11. Why should it be appealing to mathematicians? Because choosing pure –i.e. mathematical– functions as a foundation means that programs are algebraic objects. Computation is literally simplification of algebraic expressions. This is very intuitive from the point of view of a mathematician. For instance, we can use substituition of equals for equals principle as a way to reason about programs. This is also very useful from the point of view of a programmer. It even has a name in computer science. It is called referential transparency. Note that in imperative languages referential transparency fails. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 5 / 25
  • 12. Enter Haskell We will work out an example of the programs are algebraic objects approach in detail. For that we will use Haskell, an industrial strength pure functional language, named after the mathematician and logician Haskell Curry. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 6 / 25
  • 13. Enter Haskell We will work out an example of the programs are algebraic objects approach in detail. For that we will use Haskell, an industrial strength pure functional language, named after the mathematician and logician Haskell Curry. This will not be a crash course in Haskell. Instead, I will explain the syntax as we go. If you have any difficulty in reading a code snippet, please ask! Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 6 / 25
  • 14. Lists in Haskell Like the vast majority of programming languages, Haskell has data structures. One of the most common data structures in Haskell is the list structure. Here is the definition: given a type a, (like integers, floating point numbers, strings, etc.) we define [a] by structural recursion as follows: 1 [] is a list, it is called the empty list; 2 if x is an element of type a and xs is a list of elements of type a then x : xs is also list. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 7 / 25
  • 15. Lists in Haskell Like the vast majority of programming languages, Haskell has data structures. One of the most common data structures in Haskell is the list structure. Here is the definition: given a type a, (like integers, floating point numbers, strings, etc.) we define [a] by structural recursion as follows: 1 [] is a list, it is called the empty list; 2 if x is an element of type a and xs is a list of elements of type a then x : xs is also list. For instance 1 : (2 : (3 : [])) = 1 : 2 : 3 : [] is a list of integers. Haskell allows us to express this list as [1, 2, 3]. Note that here : is a actually binary operation and a list actually a term. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 7 / 25
  • 16. Concatenation Now let us define a simple function on lists. Let xs and ys be two lists (over the same type). We define the concatenation xs + +ys of xs and ys by recursion on the structure of xs as follows: [] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys). Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
  • 17. Concatenation Now let us define a simple function on lists. Let xs and ys be two lists (over the same type). We define the concatenation xs + +ys of xs and ys by recursion on the structure of xs as follows: [] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys). Let us compute an example: [1, 2] + +[3, 4] = Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
  • 18. Concatenation Now let us define a simple function on lists. Let xs and ys be two lists (over the same type). We define the concatenation xs + +ys of xs and ys by recursion on the structure of xs as follows: [] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys). Let us compute an example: [1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : [])) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
  • 19. Concatenation Now let us define a simple function on lists. Let xs and ys be two lists (over the same type). We define the concatenation xs + +ys of xs and ys by recursion on the structure of xs as follows: [] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys). Let us compute an example: [1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : [])) =1 : ((2 : []) + +(3 : (4 : [])) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
  • 20. Concatenation Now let us define a simple function on lists. Let xs and ys be two lists (over the same type). We define the concatenation xs + +ys of xs and ys by recursion on the structure of xs as follows: [] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys). Let us compute an example: [1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : [])) =1 : ((2 : []) + +(3 : (4 : [])) =1 : (2 : ([] + +(3 : (4 : []))) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
  • 21. Concatenation Now let us define a simple function on lists. Let xs and ys be two lists (over the same type). We define the concatenation xs + +ys of xs and ys by recursion on the structure of xs as follows: [] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys). Let us compute an example: [1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : [])) =1 : ((2 : []) + +(3 : (4 : [])) =1 : (2 : ([] + +(3 : (4 : []))) =1 : (2 : (3 : (4 : []))) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
  • 22. Concatenation Now let us define a simple function on lists. Let xs and ys be two lists (over the same type). We define the concatenation xs + +ys of xs and ys by recursion on the structure of xs as follows: [] + +ys = ys and (x : xs ) + +ys = x : (xs + +ys). Let us compute an example: [1, 2] + +[3, 4] =(1 : (2 : [])) + +(3 : (4 : [])) =1 : ((2 : []) + +(3 : (4 : [])) =1 : (2 : ([] + +(3 : (4 : []))) =1 : (2 : (3 : (4 : []))) =[1, 2, 3, 4] Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 8 / 25
  • 23. Naive reverse function Suppose that we want to devise a function –that is to say, write a program– which produces the reverse of a list. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 9 / 25
  • 24. Naive reverse function Suppose that we want to devise a function –that is to say, write a program– which produces the reverse of a list. Here is the obvious solution. Given a list xs let us define naiveReverse as follows: naiveReverse [] = [] and naiveReverse (x : xs) = naiveReverse xs++[x]. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 9 / 25
  • 25. Naive reverse function Suppose that we want to devise a function –that is to say, write a program– which produces the reverse of a list. Here is the obvious solution. Given a list xs let us define naiveReverse as follows: naiveReverse [] = [] and naiveReverse (x : xs) = naiveReverse xs++[x]. As an exercise show that naiveReverse [1, 2, 3] = [3, 2, 1]. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 9 / 25
  • 26. Complexity of the naive reverse function First, note that the computation of xs + +ys requires length of xs many applications of : operation. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 10 / 25
  • 27. Complexity of the naive reverse function First, note that the computation of xs + +ys requires length of xs many applications of : operation. Claim: Computation of naiveReverse xs requires 1 2n(n − 1) applications of the operation : where n is the length of xs. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 10 / 25
  • 28. Complexity of the naive reverse function First, note that the computation of xs + +ys requires length of xs many applications of : operation. Claim: Computation of naiveReverse xs requires 1 2n(n − 1) applications of the operation : where n is the length of xs. Proof. By induction on n. Base case is trivial. Suppose the statement holds for n. Let xs be of length n. Then for any x we have naiveReverse (x : xs) = naiveReverse xs + +[x]. As naiveReverse xs and xs has the same length, namely n, computation of ++ takes n applications of the : operation. On the other hand, by induction hypothesis, naiveReverse xs requires 1 2n(n − 1) applications. Adding these two yields 1 2n(n + 1), which is what we want. QED Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 10 / 25
  • 29. Complexity of the naive reverse function First, note that the computation of xs + +ys requires length of xs many applications of : operation. Claim: Computation of naiveReverse xs requires 1 2n(n − 1) applications of the operation : where n is the length of xs. Proof. By induction on n. Base case is trivial. Suppose the statement holds for n. Let xs be of length n. Then for any x we have naiveReverse (x : xs) = naiveReverse xs + +[x]. As naiveReverse xs and xs has the same length, namely n, computation of ++ takes n applications of the : operation. On the other hand, by induction hypothesis, naiveReverse xs requires 1 2n(n − 1) applications. Adding these two yields 1 2n(n + 1), which is what we want. QED So the complexity is quadratic as a function of the input length. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 10 / 25
  • 30. The Basic Idea The naive implementation of the reverse function is quadratic because ++ is expensive. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 11 / 25
  • 31. The Basic Idea The naive implementation of the reverse function is quadratic because ++ is expensive. There is a very similar situation in mathematics with an elegant solution: multiplication is expensive, however one can use logarithms to turn multiplication into addition, do the additon and come back with exponentiaiton. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 11 / 25
  • 32. The Basic Idea The naive implementation of the reverse function is quadratic because ++ is expensive. There is a very similar situation in mathematics with an elegant solution: multiplication is expensive, however one can use logarithms to turn multiplication into addition, do the additon and come back with exponentiaiton. We will use the same trick, namely we will change the algebraic structure we work in by using homomorphisms. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 11 / 25
  • 33. A Small Remark Before We Continue It is about to get technical. Without a certain background in mathematics some of the things I will talk about may not make much sense. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 12 / 25
  • 34. A Small Remark Before We Continue It is about to get technical. Without a certain background in mathematics some of the things I will talk about may not make much sense. However, you should not leave the room because Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 12 / 25
  • 35. A Small Remark Before We Continue It is about to get technical. Without a certain background in mathematics some of the things I will talk about may not make much sense. However, you should not leave the room because I will give an example for programmers, which will probably be opaque for most mathematicians, Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 12 / 25
  • 36. A Small Remark Before We Continue It is about to get technical. Without a certain background in mathematics some of the things I will talk about may not make much sense. However, you should not leave the room because I will give an example for programmers, which will probably be opaque for most mathematicians, You do not need to understand any of the mathematics here to be productive in Haskell, or any other functional programming language. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 12 / 25
  • 37. Algebra refresher: Cayley representation theorem Recall that a monoid is a triple (M, ∗, e) where ∗ is a binary associative operation on M and e is the identity element of ∗. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 13 / 25
  • 38. Algebra refresher: Cayley representation theorem Recall that a monoid is a triple (M, ∗, e) where ∗ is a binary associative operation on M and e is the identity element of ∗. Here are two important examples: 1 For any set S, the set of self maps of S, denoted by End(S) is a monoid under composition. The identity is the identity function. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 13 / 25
  • 39. Algebra refresher: Cayley representation theorem Recall that a monoid is a triple (M, ∗, e) where ∗ is a binary associative operation on M and e is the identity element of ∗. Here are two important examples: 1 For any set S, the set of self maps of S, denoted by End(S) is a monoid under composition. The identity is the identity function. 2 For any set S, the set of finite sequences with elements from S form a monoid under concatenation. The identity is the empty list. (Actually this is called the free monoid generated by S.) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 13 / 25
  • 40. Algebra refresher: Cayley representation theorem Theorem Cayley A monoid with underlying set S can be embedded in End(S). Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 14 / 25
  • 41. Algebra refresher: Cayley representation theorem Theorem Cayley A monoid with underlying set S can be embedded in End(S). Proof. One can easily check that C(s) = λs where λs(x) = s ∗ x is such an embedding. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 14 / 25
  • 42. Algebra refresher: Cayley representation theorem Theorem Cayley A monoid with underlying set S can be embedded in End(S). Proof. One can easily check that C(s) = λs where λs(x) = s ∗ x is such an embedding. Note that if a function f is in the image of C then one can recover the element it came from by applying f to the identity of the monoid. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 14 / 25
  • 43. Pushing the problem to End([a]) In End([a]), the monoidal operation, namely function composition, is very cheap. To be more precise, it requires constant time because the composition of two functions is left untouched untill someone tries to apply it to a value. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 15 / 25
  • 44. Pushing the problem to End([a]) In End([a]), the monoidal operation, namely function composition, is very cheap. To be more precise, it requires constant time because the composition of two functions is left untouched untill someone tries to apply it to a value. However, the notion of reverting only makes sense in [a] and not in End([a]). So we need to embed only the concatenation part of the problem into End([a]). Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 15 / 25
  • 45. Pushing the problem to End([a]) In End([a]), the monoidal operation, namely function composition, is very cheap. To be more precise, it requires constant time because the composition of two functions is left untouched untill someone tries to apply it to a value. However, the notion of reverting only makes sense in [a] and not in End([a]). So we need to embed only the concatenation part of the problem into End([a]). The inverse of xs is given by f xs [] where f is defined by f [] = id and f (x : xs) = f xs ◦ C([x]). Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 15 / 25
  • 46. Haskell Implementation type End s = s -> s singleton :: a -> End [a] singleton x = f where f y = x : y cayleyReverse :: [a] -> End [a] cayleyReverse [] = id cayleyReverse (x : xs) = cayleyReverse xs . singleton x naiveReverse :: [a] -> [a] naiveReverse [] = [] naiveReverse (x : xs) = naiveReverse xs ++ [x] betterReverse :: [a] -> [a] betterReverse xs = cayleyReverse xs [] Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 16 / 25
  • 47. Monoid Objects in a Category We will port our method to different domains using category theory. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
  • 48. Monoid Objects in a Category We will port our method to different domains using category theory. First, we need to translate our notions to category theory. Effectively, this means expressing everything in terms of functions and their compositions. We need Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
  • 49. Monoid Objects in a Category We will port our method to different domains using category theory. First, we need to translate our notions to category theory. Effectively, this means expressing everything in terms of functions and their compositions. We need Elements (using terminal objects) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
  • 50. Monoid Objects in a Category We will port our method to different domains using category theory. First, we need to translate our notions to category theory. Effectively, this means expressing everything in terms of functions and their compositions. We need Elements (using terminal objects) Products (expressing Cartesian product as a categorical limit) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
  • 51. Monoid Objects in a Category We will port our method to different domains using category theory. First, we need to translate our notions to category theory. Effectively, this means expressing everything in terms of functions and their compositions. We need Elements (using terminal objects) Products (expressing Cartesian product as a categorical limit) Monoids (using the “associativity” of Cartesian products) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
  • 52. Monoid Objects in a Category We will port our method to different domains using category theory. First, we need to translate our notions to category theory. Effectively, this means expressing everything in terms of functions and their compositions. We need Elements (using terminal objects) Products (expressing Cartesian product as a categorical limit) Monoids (using the “associativity” of Cartesian products) Now a monoid is a set M together with two functions ∗: M × M → M and e : 1 → M satisfying the associativity and identitiy rules. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
  • 53. Monoid Objects in a Category We will port our method to different domains using category theory. First, we need to translate our notions to category theory. Effectively, this means expressing everything in terms of functions and their compositions. We need Elements (using terminal objects) Products (expressing Cartesian product as a categorical limit) Monoids (using the “associativity” of Cartesian products) Now a monoid is a set M together with two functions ∗: M × M → M and e : 1 → M satisfying the associativity and identitiy rules. The associativity rule of a monoid M can be expressed by saying that the two functions ∗ ◦ (id × ∗) and ∗ ◦ (∗ × id) ◦ α from M × (M × M) to M are equal. (Here α(x, (y, z)) = ((x, y), z)).) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
  • 54. Monoid Objects in a Category We will port our method to different domains using category theory. First, we need to translate our notions to category theory. Effectively, this means expressing everything in terms of functions and their compositions. We need Elements (using terminal objects) Products (expressing Cartesian product as a categorical limit) Monoids (using the “associativity” of Cartesian products) Now a monoid is a set M together with two functions ∗: M × M → M and e : 1 → M satisfying the associativity and identitiy rules. The associativity rule of a monoid M can be expressed by saying that the two functions ∗ ◦ (id × ∗) and ∗ ◦ (∗ × id) ◦ α from M × (M × M) to M are equal. (Here α(x, (y, z)) = ((x, y), z)).) Exercise: Express the identity rule. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 17 / 25
  • 55. Monoid Objects in a Monoidal Category This is where the hand-waving starts. For actual definition you may use Wikipedia. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 18 / 25
  • 56. Monoid Objects in a Monoidal Category This is where the hand-waving starts. For actual definition you may use Wikipedia. First, let us forget about sets and functions and work with an arbitrary category. This means that we work with abstract objects and abstract “maps” between them. The composition f ◦ g is defined only when the codomain of g coincides with the domain of f . The only assumption about this abstract composition is associativty. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 18 / 25
  • 57. Monoid Objects in a Monoidal Category This is where the hand-waving starts. For actual definition you may use Wikipedia. First, let us forget about sets and functions and work with an arbitrary category. This means that we work with abstract objects and abstract “maps” between them. The composition f ◦ g is defined only when the codomain of g coincides with the domain of f . The only assumption about this abstract composition is associativty. Let us also forget about Cartesians product and work with an arbitrary monoidal structure. This means that we have a binary construction on our objects with a function like α –and a little bit more. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 18 / 25
  • 58. Monoid Objects in a Monoidal Category This is where the hand-waving starts. For actual definition you may use Wikipedia. First, let us forget about sets and functions and work with an arbitrary category. This means that we work with abstract objects and abstract “maps” between them. The composition f ◦ g is defined only when the codomain of g coincides with the domain of f . The only assumption about this abstract composition is associativty. Let us also forget about Cartesians product and work with an arbitrary monoidal structure. This means that we have a binary construction on our objects with a function like α –and a little bit more. It turns out that the notion of a monoid can be expressed in any category with a monoidal structure. If your category is the category of sets and functions between them and the monoidal structure is the Cartesian product then you recover the original notion. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 18 / 25
  • 59. Examples: Applicatives, Monads and Arrows But is this generalization useful? Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
  • 60. Examples: Applicatives, Monads and Arrows But is this generalization useful? You bet! Here are some examples. Let Hask be the category of types in Haskell with functions definable in Haskell and pairing (or product) as the monoidal structure. (From a strict point of view, this is not true but good enough to snatch ideas from category theory.) Then for any a, [a] and End a are monoids. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
  • 61. Examples: Applicatives, Monads and Arrows But is this generalization useful? You bet! Here are some examples. Let Hask be the category of types in Haskell with functions definable in Haskell and pairing (or product) as the monoidal structure. (From a strict point of view, this is not true but good enough to snatch ideas from category theory.) Then for any a, [a] and End a are monoids. Consider endofunctors of Hask with composition as the monoidal structure. Then the monoids are called the monads. The Cayley representation in this context is acalled the codensity monad transformation for historical reasons. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
  • 62. Examples: Applicatives, Monads and Arrows But is this generalization useful? You bet! Here are some examples. Let Hask be the category of types in Haskell with functions definable in Haskell and pairing (or product) as the monoidal structure. (From a strict point of view, this is not true but good enough to snatch ideas from category theory.) Then for any a, [a] and End a are monoids. Consider endofunctors of Hask with composition as the monoidal structure. Then the monoids are called the monads. The Cayley representation in this context is acalled the codensity monad transformation for historical reasons. In the category of endofunctors of Hask with Day convolution as the monoidal structure the monoids are called the applicatives. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
  • 63. Examples: Applicatives, Monads and Arrows But is this generalization useful? You bet! Here are some examples. Let Hask be the category of types in Haskell with functions definable in Haskell and pairing (or product) as the monoidal structure. (From a strict point of view, this is not true but good enough to snatch ideas from category theory.) Then for any a, [a] and End a are monoids. Consider endofunctors of Hask with composition as the monoidal structure. Then the monoids are called the monads. The Cayley representation in this context is acalled the codensity monad transformation for historical reasons. In the category of endofunctors of Hask with Day convolution as the monoidal structure the monoids are called the applicatives. In the category of profunctors with profunctor tensor as the monoidal structure the monoids are called the weak arrows. . . . Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 19 / 25
  • 64. Tip of the iceberg This was just one idea and its generalizations. Here is an incomplete list of other relevant pure mathematical notions, each of which could be the topic of a different talk: Free constructions (free monads, free applicatives, etc.) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
  • 65. Tip of the iceberg This was just one idea and its generalizations. Here is an incomplete list of other relevant pure mathematical notions, each of which could be the topic of a different talk: Free constructions (free monads, free applicatives, etc.) Categorical duality (comonds, cofree constructions etc.) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
  • 66. Tip of the iceberg This was just one idea and its generalizations. Here is an incomplete list of other relevant pure mathematical notions, each of which could be the topic of a different talk: Free constructions (free monads, free applicatives, etc.) Categorical duality (comonds, cofree constructions etc.) Functors (adjointness and representability) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
  • 67. Tip of the iceberg This was just one idea and its generalizations. Here is an incomplete list of other relevant pure mathematical notions, each of which could be the topic of a different talk: Free constructions (free monads, free applicatives, etc.) Categorical duality (comonds, cofree constructions etc.) Functors (adjointness and representability) Categories as databases (AQL and functorial migration) Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
  • 68. Tip of the iceberg This was just one idea and its generalizations. Here is an incomplete list of other relevant pure mathematical notions, each of which could be the topic of a different talk: Free constructions (free monads, free applicatives, etc.) Categorical duality (comonds, cofree constructions etc.) Functors (adjointness and representability) Categories as databases (AQL and functorial migration) Curry-Howard correspondence . . . A lot of exciting things are happenning here! Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 20 / 25
  • 69. The Example I Promised to Programmers At this point, most programmers in the audience should be thinking “I’ve been coding without knowing/understanding any of these abstract mathematical concepts. Do I have to know/understand them?” Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 21 / 25
  • 70. The Example I Promised to Programmers At this point, most programmers in the audience should be thinking “I’ve been coding without knowing/understanding any of these abstract mathematical concepts. Do I have to know/understand them?” The answer is no. This was mostly meant for mathematicians. One can use these tools without understanding the theoretical background. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 21 / 25
  • 71. The Example I Promised to Programmers At this point, most programmers in the audience should be thinking “I’ve been coding without knowing/understanding any of these abstract mathematical concepts. Do I have to know/understand them?” The answer is no. This was mostly meant for mathematicians. One can use these tools without understanding the theoretical background. However a certain shift in mentality seems to be unavoidable. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 21 / 25
  • 72. The Example I Promised to Programmers At this point, most programmers in the audience should be thinking “I’ve been coding without knowing/understanding any of these abstract mathematical concepts. Do I have to know/understand them?” The answer is no. This was mostly meant for mathematicians. One can use these tools without understanding the theoretical background. However a certain shift in mentality seems to be unavoidable. For that reason, I will give an example of what you can do with Haskell from our own code base. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 21 / 25
  • 73. Asynchronous Actions Here is the problem: Suppose that we have some asynchronous actions each of which can either return a value or fail with an error message. We want to capture the first value returned by these actions. However, if they all fail, we want to have a list of all the error messages returned. Optional: The error messages should be ordered chronologically. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 22 / 25
  • 74. Asynchronous Actions Here is the problem: Suppose that we have some asynchronous actions each of which can either return a value or fail with an error message. We want to capture the first value returned by these actions. However, if they all fail, we want to have a list of all the error messages returned. Optional: The error messages should be ordered chronologically. Please take a moment and try to solve this problem in your head using your favourite language. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 22 / 25
  • 75. Asynchronous Actions Here is the problem: Suppose that we have some asynchronous actions each of which can either return a value or fail with an error message. We want to capture the first value returned by these actions. However, if they all fail, we want to have a list of all the error messages returned. Optional: The error messages should be ordered chronologically. Please take a moment and try to solve this problem in your head using your favourite language. Our solution will depend on Async, a library developed by Simon Marlow. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 22 / 25
  • 76. Haskell Implementation pickFirstElligible :: [Async (Either a b)] -> IO (Either [a] b) pickFirstElligible allActions = run [] allActions ‘finally‘ mapM_ cancel allActions where run errs actions = if null actions then return $ Left $ reverse errs else do (action, res) <- waitAny actions case res of Left err -> run (err : errs) (delete action actions) Right val -> return $ Right val Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 23 / 25
  • 77. Two mottos Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 24 / 25
  • 78. Two mottos There is nothing more practical than a good theory. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 24 / 25
  • 79. Two mottos There is nothing more practical than a good theory. In theory, there is no difference between theory and practise. In practise, there is. Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 24 / 25
  • 80. Thank you for listening! Sonat S¨uer (Picus Security) An Invitation to Functional Programming February 14 2018 25 / 25