Monads

Monoids

Conventional approach

Combine several components together of type A to generate a "network" or "topology" of type B

Maths Incoming

( Prepare yourselves )

1 + 2 = 3

1 + (2 + 3) = (1 + 2) + 3

1 + 0 = 1

0 + 1 = 1

That's all

Thinking

Like a
Maths Person

What do these things have in common?

How can we generalise these things? 

1 + 2 = 3

1. We've got a bunch of things

2. We've got some way of combining two of them

3. And the result is another one of these things

What does this work for?

*

min/max

and/or

list/string concatination

Why would I even care?

Why is it interesting that the operation returns another thing of the same type?

You can chain together multiple objects using the same operation

1 + 2

1 + 2 + 3

1 + 2 + 3 + 4

1 == 2 == 3 == 4

the result is another one of these things

Closure

1 + (2 + 3) = (1 + 2) + 3

tldr; the order we apply our operation doesn't matter.

We'll get the same results either way

 

((1+2) + 3) + 4

1 + (2 + (3+4))

(1+2) + (3+4)

1 * (2 * 3)

(1 * 2) * 3

1 - (2 -3)
(1 - 2) - 3

What else does this work for?

max( max(12,2), 3) 

max(12, max(2,3)
 

the order you apply the operation doesn't matter

associativity

1 + 0 = 1

there is a special kind of thing ("zero") that, when you combine it with something, just gives you back the original something, as if nothing had happened.

 

Let's see if we can extend this "zero" concept to our other examples

10 * 1
1 * 30

True and True
True and False

False or True
False or False

"" + "hello" = "hello"
[] + [2,3] = 23

This is called the

identity element

1 + 2 = 3
1 + (2 + 3) = (1 + 2) + 3
1 + 0 = 1

You start with a bunch of things, and some way of combining them two at a time.

1. (Closure): The result of combining two things is always another one of the things.

2. (Associativity): When combining more than two things, which combination you do first doesn't matter

3. (Identity element): There is a special thing called "zero" such that when you combine any thing with "zero" you get the original thing back.

Why should I care?
( as a developer )

Closure

You can convert operations to work on lists

1 + 2 + 3 + 4 + 5
vs
reduce/fold (+) [1,2,3,4,5]

Associativity

Divide and conquer algorithms

Parallelization

Incrementalism

Another optimisation

((((((5 * 5) * 5) * 5) * 5) * 5) * 5) * 5

7 multiplications

((5 * 5) * (5 * 5)) * ((5 * 5) * (5 * 5))

= (25 * 25) * (25 * 25)

= 625 * 625 = 390625

Identity

How can I use reduce on an empty list?

When using an incremental algorithm, what value should I start with when I have no data?

Monads

By ..

Monads

  • 1,785