KEMBAR78
Introduction to functional programming | PDF
Functional programming
Functional Programming (Languages) FP(L)
Agenda
● Why functional programming?
● Functional Programming
● Benefits of FP
● Concurrency
● How to program functionally
In the beginning there was ...
Lambda calculus
● Theoretical framework
● Describes functions and their evaluations
● Basis of almost all FPL today
Why is functional programming important?
The benefits of functional
programming
● succinct, concise and understandable code
● offers different programming perspective
● FP becoming more accessible
● concurrency / parallelism without tears
Why FP is important?
Row 1 Row 2 Row 3 Row 4
0
2
4
6
8
10
12
Column 1
Column 2
Column 3
Wirth's Law
Software is getting slower more rapidly than
hardware becomes faster
FP != FPL
If all of these are functional programming
(languages), isn't it overwhelming and difficult?
Not really. But why?
What is functional programming?
What is a functional programming language?
Functional programming is just a style
Programming styles
Declarative vs. Imperative programming
What? vs. How?
What is object-oriented
programming?
● Reuse code via classes
● Eliminate bugs
– Encapsulation
– Data hiding
Functional programming
● Reuse code via function composition
● Eliminate bugs
– Immutability
– Pure functions
Programs as functions
● No loops but recursion
● Minimise number of variables
● no assignment operation
● only constants, parameters and values
The dark side
too much recursion can overflow the stack
(without tail-call optimization)
high memory consumptions from creating so
many objects
No variables, no assignment – No
problem
● No notion of the internal state of a function
● referential transparency
● value semantics
Referential Transparency
An expression is said to be referentially
transparent if it can be replaced with its value
without changing the behaviour of a program
25 == 5 * 5
Value semantics
It means for an object that only its value counts,
not its identity
Coping an object doesn't change the behaviour
of your program
Pure Function
● Always evaluates to the same result
● Evaluation does not cause side effects
What does it mean in practice?
No bugs due to nasty side effects
Mutable state
Map<Person, String> map = …
Person p = new Person('John');
map.put(p, "Hey, there!");
p.setName("Dark Lord");
Oops!
map.get(p); // => null
Immutability
“Object-oriented programming makes code
understandable by encapsulating moving parts.
Functional programming makes code
understandable by minimizing moving parts.”
— Michael Feathers, author of Working with Legacy Code, via
Twitter
● Data once created are never changed
● Need to “update” your data? – create new one
● Safe to share data between threads
HOF
Higher order function
– Takes one or more functions as an input
and/or
– Outputs function
Ruby
● Map
● Each
● Reduce
● Inject
● Select
Ruby
def twice(f, x)
f.call(f.call(x))
end
f1 = ->(x){ x / 3 }
print twice(f1, 9) # 1
JavaScript
function twice(f, x){
return f(f(x));
}
function f(x){
return x*3;
}
twice(f, 7); // 63
Higher-order functions start to shine when you
need to compose functions
JavaScript
function filter(array, test) {
var passed = [];
for (var i = 0; i < array.length; i++) {
if (test(array[i]))
passed.push(array[i]);
}
return passed;
}
function map(array, transform) {
var mapped = [];
for (var i = 0; i < array.length; i++)
mapped.push(transform(array[i]));
return mapped;
}
function average(array) {
function plus(a, b) { return a + b; }
return array.reduce(plus) / array.length;
}
function age(p) { return p.died - p.born; }
function male(p) { return p.sex == "m"; }
average(ancestry.filter(male).map(age))
Lazy evaluation
● Delaying evaluation of an expression
● Reduction of memory footprint as values are created
when needed not when they are declared
● Potential to construct infinite data structures
● Requires pure functions as order of operations becomes
indeterminate
Lazy Fibonacci
● Haskell
● Infinite list
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
● Take only required Fibonacci numbers
Memoization
● Storing the result of function calls
● Returning the cached result
● Trade-off between function time cost and space
cost
● Run-time not compile-time optimisation
You can program functionally in a variety of
programming languages
A functional language provides 'sane' defaults
Why is FP important? (again)
● formal provability
● code comprehension modularity
● unit testing and debugging
● automation
● maintainability
● hot code deployment
Provability
simpler execution model makes program proving
easier both for computers and humans
Code comprehension
easier to understand and reason about because
you don't have to worry about what is happening
behind the scenes
Modularity
modular design brings with it great productivity
improvements. Small modules can be coded
quickly and easily and have a greater chance of
re-use which leads to faster development of
programs.
Additionally, the modules can be tested
independently, thus helping to reduce the time
spent unit testing and debugging
Testing, debugging & automation
● PF is much easier to reason about
● specific arguments always return specific results
● problems are easy to troubleshoot/duplicate because no
state or external dependencies
● automation is simplified due to lack of environmental,
state or configuration concerns
Maintainability
easier to maintain as you don't have to worry
about accidentally changing anything outside a
given function
Concurrency
Compilers think, too
In the purely functional world, the compiler does
not need proof of non-interference. It is built into
the programming language.
Implicit parallelism is free in functional
programming languages.
Sadly, this story is naïve and unrealistic and yet it
contains the key to a parallel world.
In the imperative world mutation creates too few
opportunities for automatic parallel execution
In the functional world a lack of dependencies
means too many opportunities for automatic
parallel execution.
The imperative world will see explicit parallel
programming and the big battle against race
condition bugs.
The functional world will provide explicit parallel
programming with fewer race conditions.
How to program functionally?
Avoid side-effects
● do not modify variables passed to functions
● do not modify any global variables
● Use higher-order functions
● Limit variable assignment
● Same input → same output
● Don't share state
Does order matter?
Order can be a side effect
● Use immutable data
● Lazy evaluation
Decompose problems into functions
(whenever you can)
Questions
Any questions?
Slack #fp
Resources
http://eloquentjavascript.net/05_higher_order.html
http://www.sitepoint.com/functional-programming-tec
hniques-with-ruby-part-ii/
http://www.functionalprogramming.com/history.html
http://www.cs.kent.ac.uk/people/staff/dat/miranda/w
hyfp90.pdf

Introduction to functional programming