Woo! Look at them go! If you throw on this then it's like a 2 hour dance party!
=<< Just Wait a Sec... >>=
This slide needs to be here to let the confetti settle otherwise the next slide lags even more lol... Just wait til the confetti goes away and continue.
=<< What's up with that Title? >>=
It’s functions, pure functions! Pure functions and their values, PURE FUNCTIONS FOREVER AND FOREVER AND FOREVER A HUNDRED YEARS monad... some... things... Me and monads runnin' around and...applicative functor time... a- all day long forever... All a - a hundred days applicatives and functors! Forever a hundred times.... OVER and over monad transformers... adventures dot com... W W W dot at lambda calculus and category theory dot com w..w..w... function composition adventures... Ah- hundred years… Every minute referential... transparency dot com.... w w w a hundred times... composition dot com...
Fig 1.1 What most people thing a typical functional programming advocate looks like
Wide-eyed Crazy Functional Programmers
Some people were curious about the title, so I figured I'd clarify what it means - functional programmers have a reputation of...
Being eccentric wide-eyed crazies with wild ideas
Spouting nonsense like "monads" and "functors" every 2 seconds
Being bald
=<< Obligatory Quote >>=
If you wish to build a ship, do not divide the men into teams and send them to the forest to cut wood. Instead, teach them to long for the vast and endless sea.
- Some French Guy. Idk. I'm not cultured. I'm Australian.
Some Framing
My goal is not to teach you functional programming, my goal is to spark curiosity
And I think this obligatory quote (every good talk has a quote) conveys the framework I used when writing these slides
Also we like boats and ships and stuff like that here, so make sense I guess
I'm not gonna make you build the ship, I'm gonna try make you curious about the sea that is functional programming
With that in mind, don't take any code examples too seriously, they are to demonstrate the big picture idea
=<< What is this Talk About? >>=
This talk is not about:
Haskell
Convincing you to stop using whichever language you like
Mathematics
Teaching Violation!
They say you should never say what something is not when teaching
But screw that, anarchy! Yeah!
=<< What is this Talk About? >>=
Perspective
What It Do, Then?
So what is it about?
When trying to explain to someone why they should learn functional programming, there are many perspectives to try explain it from.
For this discussion, I've settled on a very meta one. Perspective itself.
=<< What is Functional Programming? >>=
Programming with functions.
Who could have guessed!
=<< What is Functional Programming? >>=
Programming with functions.
No, really. Everything is a function.
=<< What is a Function? >>=
A mapping between sets that associates every element of the first set to exactly one element of the second set.
Regarding Functions
These aren't like procedural functions - "function" is a misnomer in that context. They are really procedures or subroutines (hence the name procedural)
A function is a mapping. It's equivalent to something like an array in PHP. It associates one value to another one
In the same way that a PHP array cannot mutate state, a function cannot
These are called "pure functions", but I'll just say "functions"
Mat asked a question about "impure functions"
An impure function involves side effects. For example:
function readFileAndAdd2(string $filePath) : int {
$number = file_get_contents($filePath);
return $number+2;
}
is impure because it could be called with the same input and give different outputs (if the contents of the file at $filePath change).
So how can you possibly do I/O in a pure functional language?
It is possible, but that's beyond the scope of this talk (maybe another dev training?)
=<< What is a Function? >>=
No equivalent constructs for:
For loops
While loops
Gotos
Variables*
Probably a bunch of other constructs I forgot
*In pure functional programming, there are true variables. That is, once you declare the value of a variable, you cannot change it. Contrast this with procedural languages where you can reassign a variable whenever you like.
Consequences
As a consequence, of having only pure functions, we have no more control structures D:
That raises the question... (go to the next slide xD)
=<< Huh? >>=
Who in their right mind would wanna do that?!
Yeah, Who? Crazies, No Doubt
It seems paradoxical, features have been removed, but somehow functional programming is just as good? Maybe better?
How can taking away all the tools we use to write programs be a good thing?
It actually makes no difference. You can accomplish anything in FP that you can accomplish in a procedural language, and gain some cool new superpowers
=<< Huh? >>=
Why tho?
Learning is good
Brain plasticity
Greater perspective
Learn for Big Brain
Learning functional programming is gonna require you to wrestle your brain in to shapes it's never taken before. Which will leave it with the plasticity to learn a greater variety of things you encounter.
It will also make the math/logic part of your brain very buff
As mentioned, there is no maths in this talk, but if you learn functional programming you will get buff maths brain
And as we know, the brain has 3 main cortexes: The passion cortex, the power cortext, and the maths/logic cortex
For the purposes of programming, we need a buff maths/logic cortext, learning functional programming will make us better programmers in general
=<< Paradigms >>=
Paradigms
=<< Paradigms >>=
Declarative
Functional
Haskell
Elm
Elixir
Clojure
Imperative
Procedural
PHP
C
Java
BASIC
The Big Two
Here are the big two paradigms, and inside those we see sub-paradigms.
And then in those there are some languages that embody that paradigm (there are more places languages can exist, for example SQL is declaritive but not functional, and Assembly is imperative but not procedural)
Marina made a comment that thinking about SQL while reading these slides is helpful - and I think that's true
In SQL you express things in terms of relations, and there are no for loops, while loops, gotos, etc
For this talk it's OK to just think of declaritive and functional as interchangeable, same with imperative and procedural
Foreshaddowing: Imperative and declaritive are both words used to describe human language
Learning a new paradigm is beneficial the same way learning a new human language is. It makes you better at programming and communicating.
=<< Gramatical Mood >>=
Declarative
A sentence which expresses a statement of fact.
He runs.
I like climbing.
Ice is cold.
Mathieu is shredded.
ImperativeA sentence which expresses instructions, or requests.
Shut the door.
Don't eat my burger.
Let's go to the pub.
Don't make eye contact with Craig.
We can see here that in the declaritive mood you express statements of fact. They aren't instrcutions
Contrast this with the imperative style of expression where there is a very clear instruction to carry out
=<< Gramatical Mood >>=
Declarative
This is this.
Imperative
Do this.
This is the simplest way I can think to express difference
=<< Big Brain Moment >>=
Programming languages ARE human languages.
We don't write programs for computers We write programs for other humans
Unless your writing machine code or something like that...
=<< Why is declaritive mood good? >>=
Atemporality Independant of or unaffected by time.
I Can See Through Time!
In both the human language case, and the programming case, we give up our "instruction words" (in the case of programming, this is for, while, goto, etc)
Surely giving instructions is useful, otherwise how do you do anything?!
Do we get something good in return? Yes! We get atemporality
This is super powerful and quite different from how we normally write programs
When we write in a procedural language we have to think about how things change over time
=<< Why is declaritive mood good? >>=
Declarative programs express what they actually do leaving more "brain space" to focus on solving the problem.
Expressivity
In an imperative paradigm, thinking about the program means thinking about changes over time - which means we have to keep track of state in our head
In a declaritive paradigm, thinking about the program means thinking about relationships - which means we look at what the thing is, how it relates to the other thing, and move on
=<< To Recap >>=
Why tho?
Because sometimes there is such a thing as too much freedom
Functional programming is awesome because it stops you shooting yourself in the foot
"Constraints liberate, liberties constrain"
There are also classes of problems where the declaritive style is a more elegant way of expressing the solution
Some problems are very difficult to solve in an imperative way.
Especially when talking about events that are happening in parallel and may run at different speed/times
In the imperative paradigm, you quite easily come up against data races by virtue of the way the program is expressed
Functional programming takes away entire classes of problems by removing the "instruction words" - no more data races
If you ever used JavaScript before promises were a thing, I'm sure you've felt the pain
=<< Some Code (Finally) >>=
My favourite example
Consider:
x = x + 1;
and:
function repeat(x) {
return x + repeat(x);
}
OK, so what?
In the declaritive paradigm, this code hangs while this code runs. In the imperative paradigm this code hangs, while this code runs.
Interactive Slide!
Hover over the "this" words in the text box! Notice that the code which hangs is flipped in each paradigm!
This code is not any specific language. It's one I made up although it looks similar to other languages
The idea is to parse it in the declaritive and the imperative style to see the difference
=<< Some Code (Finally) >>=
x = x + 1;
Declarative
"x is the same as itself plus one."
Complete nonsense!
Imperative
"Evaluate the thing on the right of `=` then store it in the thing on the left of `=`."
A list of instructions that can be followed.
Reminder!
In the declaritive paradigm, = means that two things are one in the same - which leads to a contradiction in our example
In the imperative paradigm (assuming x is defined) there's no problem - we just add 1 to x, then save it back in x
=<< Some Code (Finally) >>=
function repeat(x) {
return x + repeat(x);
}
Declarative
"The repeat of `x` is `x` appended to the repeat of `x`"
An infinite list of `x`!
Imperative
"To evaluate the repeate of `x`, first evaluate the repeat of `x`"
...Yeah, you see the problem?
Atemporality
Here we are starting to touch on atemporality
The declaritive style does not read the definition as instructions. It's not things happening over time. It just is what it is. It's a list of whatever you pass in repeated forever
=<< Big Brain Moment >>=
Programming languages ARE human languages.
Recap/Reinforcement
Imperative tells you what to do
Declaritive tells you what things are
=<< Some Code (Finally) >>=
Real Haskell code that runs
repeat x = x ++ repeat x
threeFs = take 3 (repeat "f")
> "fff"
The first line is the Haskell way of defining the repeat function from before
And we read this as: "threeFs is the first three elements in an infinite list of fs"
And that's totally fine! If you have an infinitely long list of fs then of course you can just take the first 3
It's a but unfortunate that the function to get n elements is called "take" because that's kinda imperative, but whatever
=<< Some Code (Finally) >>=
Real JavaScript code that hangs
function repeat(x) {
return x + repeat(x);
}
threeFs = repeat("f").substr(0,3);
> InternalError: too much recursion
By contrast, this reads as "First compute an infinite list of fs" - which is clearly problematic
It's left as an exercise to the reader to try work out why the x = x + 1 example would hang in Haskell
=<< Big Brain Moment >>=
What did declaritive mode give us?
Atemporality
The ability to wield infinity!
Big Brain Moment Two!
How cool is that? Because we can express what things are, we can express an infininte list!
Often when we write programs, we have to worry about things cascading out infinitely, but not in the declaritive paradigm!
None of the declaritive version of the program relies on us traking changes anywhere. We just need to know what a thing is and how it relates to another thing
And if that thing happens to be infinite, who cares! That's just what it is
=<< Promises >>=
Promises
Seems like an odd tangent but let's go with it. And just as before, I'm gonna break one of the carinal rules of teaching by telling you what promises are not...
=<< Promises >>=
>:(
>:(
>:(
>:(
>:(
>:(
>:(
>:(
>:(
>:(
Promises do not make things asynchronous!
There's a lot of misleading information out there about promises
Some people believe that promises "make things asynchronous", but this isn't true
You can have perfectly synchronous promises, the thing you pass as a callback to a promise does not get "run in the background" or anything like that
=<< Promises >>=
The real promises
What problems do promises solve?
Asynchronous request management
Error handling for computations which may fail
Probably more too
What are promises then?
A value (which may or may not be available yet) wrapped in some additional context
Functions to instantiate the wrapper (`Promise.resolve`, `Promise.reject`)
A rule for composing these wrapped values (`then`)
The "value" is where the asynchronous part comes in
That value may become available later, but it may just be there the entire time as well
=<< Promises >>=
Terminology/syntax recap
JavaScript arrow functions
x => x + 1;
is equivalent to:
function(x) {
return x+1;
}
Composition
A method of combining two things of the same type in to another thing that is also of the same type
Regarding Composition
You may have come across function composition. There's lots of different kinds of composition, but function composition is incredibly common, especially in programming. But we'll talk about the composition of promises.
In both cases the idea is the same. Function composition lets you combine two functions in to another function. Promise composition lets you combine two promises in to another promise
=<< Promises >>=
Promise composition
The `then` method of a promise accepts a function as an argument. This function takes a value and returns a new promise. The new promise "combines" the previous two using the "composition rule" given to `then`.
Promise.resolve("Some value").then(x => Promise.resolve(x + " and another value")).then(x => Promise.resolve(x + " and another one!"));
There are three promises in the above snippet. One, two, three.
Promise.resolve("Some value").then(x => Promise.reject("It's all gone wrong")).then(x => Promise.resolve(x + " and another one!"));
The above snippet still results in a promise, but it is a "failed" one. Any subsequent `then` after the `reject` has no effect.
Interactive Slide!
Hover over "one", "two", and "three" to see the promises highlighed
The first one is all by itself
The second one is the composition of the first one using the composition rule (the function passed to `then`)
The third one is the composition of the second one using the composition rule (the function given to `then`)
The `then` method accepts a function which:
Will be passed the previous promise's wrapped value
Causing it return the next promise
Which will give its wrapped value to the function passed to the next `then` method
It's very important to realise that we are passing a function to then, not a value, it's not actually doing anything when we set up the promise chain
=<< Promises >>=
OK great but who cares?
We are declaring how we want promises to compose
The order that the promises actually resolve their values in is not important
In other words, we don't have to worry about timing anymore
We can declare a failure anywhere in the chain
Pls Note
Since this is JavaScript, you can mutate state in the functions that are passed to "then"
But that's beside the point I'm trying to demonstrate, and you shouldn't really do that anyway
=<< Promises >>=
atemporality?
declaritive?
functions?
composition?
This sure is starting to sound familiar.
=<< Big Brain Moment >>=
Woah!
JavaScript
Promise.resolve("We start here")
.then(x =>Promise.resolve(x + " then get here"))
.then(x =>Promise.resolve(x + " and finally here!"))
Haskell
Right("We start here")
>>= (\x -> Right (x ++ " then get here"))
>>= (\x ->Right (x ++ " and finally here!"))
Interactive Slide!
Hover over the language elements to see how they pair up in each language!
Promises are very similar to a type in Haskell called "Either". "Either" can be instantiated with `Right` or `Left` which correspond to `resolve` and `reject`, respectively
It does not matter what order the promises resolve in, the final promise will always be resolved with "We start here then get here and finally here"
Bas made a good point that when looking at the calls to "then" you think about the things happening one after another.
While that's true, what `then` does is describe the way to combine the results once they arrive
The "We start here" result could come from a web request that takes 10 seconds, whereas the other strings could resolve instantly, but the final promise would still be "We start here then get here and finally here" - even though that was not the order we got the results
Be careful, the `x` in each "then" call is not the same `x`. It's part of the function which is being passed to then, which means it is in a completely different scope. The purpose of the function is to describe what you want to happen
It's hard to untwist your brain from thinking about promises in the procedural way - this is what I meant by "wrestling your brain in to new shapes" :)
In this example, there is nothing asynchronous happening, but it's not much work to adapt it so there is. I mainly wanted to really the similarities with haskell
How cool is it that these look so similar?
As mentioned, in the JavaScript version, you could mutate something inside the `then` functions - but this would absolutely lead to data races
In Haskell, you cannot do that, which is one of the ways it stops you shooting yourself in the foot
Noel made an interesting comment that JavaScript added async/await as "syntactic sugar" to make this kind of code look more imperative.
And I was pleased to say that the exact same thing exists in Haskell :)
=<< Big Brain Moment >>=
Woah!
JavaScript
Promise.resolve("We start here")
.then(x =>Promise.resolve(x + " then get here"))
.then(x =>Promise.reject("Oh noes!"))
.then(x =>Promise.resolve(x + " and finally here!"))
Haskell
Right("We start here")
>>= (\x -> Right (x ++ " then get here"))
>>= (\x ->Left ("Oh noes!"))
>>= (\x ->Right (x ++ " and finally here!"))
You Were Doing FP all Along!
Likewise, we can put a failure anywhere in the chain. It doesn't matter if the failure happens first, last, or anywhere in between. The result is always a failed promise of "Oh noes!"
So, if you've ever used promises, you've been doing declaritive style programming without even realising it!
They give us some new powers, we can now write atemporal code, which explains why they emerged in JS, a place where people are constantly dealing with requests that can finish in any order
So it's super cool that people using a language very far removed from haskell ended up solving the problem in the same way
Although both are independed discoveries, I don't think it's a coincidence promises appeared given the nature of the JS world.
=<< Composition >>=
Composition
The Section on Composition!
This gets its own section because it is not just important to programming, it's important to life in general
=<< Composition >>=
=<< Composition >>=
If we can go from here to here
=<< Composition >>=
If we can go from here to here
And we can go from here to here
=<< Composition >>=
If we can go from here to here
And we can go from here to here
Then the composition (if it exists) goes from here to here
Coins and Pipes!
Keep in mind the the composition of A->B and B->C is not gauranteed to exist!
I'm using coins and pipes to demonstrate, but the coins and pipes could be anything... Functions, promises, etc.
Stop reading here!! After reading the next slide come back to this one pls :)
We want to go from A to C - but maybe that's really hard (I accidentally illustrated that in the diagram! The pipe from A to C is really long! But the A->B->C route is short!)
Perhaps someone worked out how to go from A to B, and someone else worked out how to go from B to C
If we're in a system where composition is possible, then we just solved the problem!
This is the natural way people solve problems
We like to break things up in to small chunks and solve the small bits and then put them back together
You probably do it when you're writing software at Moodle!
Stop reading here!! After getting to the "What's this got to do with FP" slide, come back pls :)
Maybe A->B has a side effect, this means when we call B->C with the result from A->B, it may not be the same as calling A->C. The point of composition is that the outcome of calling both should be indistinguishable.
Procedures in imperative languages (what most programmers call functions) are a short sighted attempt at composition, we wanted a way to break things up, and sure... You can put functions together in imperative languages and it kinda works, but it's not the same as true composition
In the functional paradigm, composition is gauranteed because functions cannot have side effects
=<< Composition >>=
OK great but who cares?
Big problems can often be chopped up in to smaller, easier to solve problems. If we can be clever about how we chop them up, such that the solutions to the individual problems can compose together to form a full solution, then we can infinitely speed up the process by adding more workers!
Remember to go back to the previous slide!
=<< Composition >>=
Examples
The pyramids
The LHC
McDonald's
Moodle!
Composition Power!
The pyramids were build by having loads of peope work in parallel
Same with the LHC - I don't believe there is a single person in the world who fully understands it
But with lots of people working together we can create this amazing thing which recreated conditions similar to that at the near-instant our universe began!
That's pretty amazing
And with McDonald's - Instead of having one chef "make a burger" staff make individual parts of the burger and compose it together (I think McDonald's was the first place to do this)
You can make a lot more burgers that way!
And Moodle does it too! Let's think about how we tackle projects...
=<< Composition >>=
"With these biceps I can solve ANYTHING"
Do we get one ultimate developer to smash out the whole thing? idk about you, but I wouldn't be keen to work with this person. Check out this story.
=<< Composition >>=
No, you get friends to take a piece and help!
henlo
henlo
henlo
henlo
henlo
henlo
Teamwork!
Of course not, we do it as a team!
This is why it's worth spending the time to plan things and figure out how to "chop up" the work
It's very important to make sure the way we "chop" the problem allows the solutions to be composed together later
=<< Composition >>=
Composition is nature's greatest hack
Why Was All that Relevant?
My goal here was to convince you that composition is fundamental to the way we think
Humans are amazing for our ability to break down problems in to manageable chunks and then compose them together - I don't think other animals do that
Which is probably a big part of how we dominated this planet so fast
At its core, composition is about relationships, and building complexity by combining them. Hey, wasn't the whole declaritive thing about relationships?
At the beginning I said in the declaritive paradigm we express things in terms of relationships...
And that brings me to the final point
=<< Composition >>=
What's this got to do with FP?
When writing programs (as an individual in this case, not as a group) we naturally want to break the solution up in to "building blocks" that we put together to solve the problem (it's composition again).
The building blocks you use matter. Some compose better than others. Because of all the restrictions the functional paradigm places on the programmer (lack of mutation, lack of control flow), functions in a pure language are naturally well-suited to composition.
This is becoming more relevant than ever in the age of parallel computing
Functional programming is great because it gaurantees composition
In a procedural language, things don't necessarily compose
The building blocks we use for our compositions matter (whether it be programs, teamwork, whatever)
The restrictions that the functional paradigm places on you means you cannot work with blocks that do not compose
So by taking away our "instruction words" we have gained another powerful tool: composition
Remember that slide I said to go back to (the coins and pipes diagram)? Do that now pls! Then come back here cos there's a few more slides after this one.
=<< Closing Notes >>=
FP is awesome because:
By taking away convenient, but dangerous tools we are left with tools that are incredibly powerful, but more difficult to wield
In particular
Atemporality: The ability to express things independant of time
Infinity: Infinite recursion can't stop you now!
Composition: The fundamental way humans solve problems is available to you at all times
New super powers!
=<< Closing Notes >>=
Very big brain thoughts:
We work across multiple timezones, so being able to solve problems in a time-independant way seems appealing, doesn't it?
Moore's law is coming to an end, now the focus is shifting to parallel computing
Imperative paradigms will not be the right tool for this
Either we'll see a shift to declaritive style programming
Or we'll make life hard for ourselves real fast
Maybe quantum mechanics is so damn confusing because at a certain point we can't decompose things anymore?
After all... why should The Universe conform to the way our brains want it to be...
In regards to Moore's law, I personally hope we start seeing a paradigm shift soon. Because that's the definition of madness really. Doing the same thing over and over but expecting different results.
Other analogies like the frog in slowly boiling water come to mind
And that's about it really!
Thanks for participating!!
If nothing else, I really hope you're now just a little bit more curious about functional programming
And even though functional programing is not incredibly relevant to our roles just now, learning more about it will make you a better programmer, and that benefits everyone :)
If you have any questions please message me, I'm always happy to talk about programming
I'd suggest going to the pub to talk about it, but, well, we can't do that just now
Bas mentioned that Haskell has a reputation for being academic
It's true that it was initially written for academic purposes
But that was over 30 years ago and it has now evolved in to something that is usable in production
Bas also asked about real world Haskell applications, here's a few I know of
Facebook's spam filter is written in Haskell (and they even contributed back to the Haskell project)
Loads of banks use it for the reason that it's hard to write software that "goes wrong" in Haskell
Target use a program written in Haskell to optimise supply chains