Functional Programming
[introduction]
Le Plan- Motivations- Definitions and Examples
What makes programming so hard?
“Controlling complexity is the essence of computer programming.”- Brian Kernighan
Complexity comes from input and state.
Possible Inputs
Possible States
Possible OutcomesX =
We should aim at reducing the input and state space.
Possible Inputs
Possible States
Possible OutcomesX =
In Object-Oriented programming, everything* is an object.
Objects combine data and behavior.
Objects are state machines.
A = xB = y
A = x’B = y’
A = x’B = y
A = xB = y’
Most objects are badly designed state machines.
A = xB = y
A = x’B = y’
A = x’B = y
A = xB = y’
Large state space are hard to reason about.
Concurrency adds new visible states.
A = xB = y
A = x’B = y’
A = x’B = y
A = xB = y’
How can we write correct code if we can’t reason about it?
Let’s add more unit tests!
Let’s add more unit tests!
Definitionsand
Examples
Functional Programming imposes constraints that eliminate states and ease reasoning.
Functional Programming is about values, functions and types*.
Values are immutable.
What about data structures?Can they be values?
Persistent data structures create a new updated version. They are immutable.
v
v
Nil
Immutability eliminates state and means you can safely share the reference.
A function takes arguments and produces a result.
(Pure) Functionshave no side-effects.
Side-effects examples:- write to disk- read from stdin- throw an exception- change a state
Having no side-effecthelps reasoning about code.
Having no side-effect simplifies testing.
Errors are handled by returning them as results.
Updating a state is done by creating a new instance with the updated state.
For other necessary side-effects, push them on the boundaries.
Looping can be implemented with recursion*.
A high-order functions takes functions as parameters and/or produces a function.
Types define classifications of values.
With types, the compilercan verify some aspects of correctness.
Object-Oriented is about semantic.
Functional Programming is about shape.
Reuse by shape is more powerful than reuse by semantic.
BUT understanding shape is harder than understanding semantic.
Summary
- Functional programing: immutable values, pure functions and precise types*.
- Benefits are:- Simple code- Concurrency and Parallelism for free- Easy to reason about- Reusable