From Imperative to
Functional Programming
Alex Bunardzic, January 2015
History of Computing
• World War II — US Army & Navy artillery ballistics
• Manual calculations not feasible
• In February 1944 IBM delivered Automatic Sequence
Controlled Calculator (ASCC), a.k.a. Mark I — weighed 5 tons,
had 750,000 parts and could perform 3 operations per second
2
Two Paradigms
Alonzo Church
Lambda calculus
(Declarative)
Alan Turing
Turing machine
(Imperative)
3
What’s the Difference?
• Programming using declarative paradigm is like
explaining your problem to a mathematician
• Programming using imperative paradigm is like
explaining your problem to an idiot
• Granted, it is much easier to explain your problem to
an idiot, because the idiot doesn’t have any opinions
and will not push back
4
Functional Paradigm
• Set of ideas, not a set of strict guidelines
• Deals with calculations (algebra)
• Uses functions to do that
• Doesn’t use variables
• Doesn’t use assignments
• No conditional statements
• No loops
5
FP Outlaws Destruction
• Not possible to destroy anything within the FP world
• The only possible thing is production
6
Stateless
• Ignorant of the past
• Functional programs perform every task as if for the
first time ever (idempotency)
• Functional programs do not maintain state
• “Good thing about telling the truth is that you don’t
have to remember anything” — Mark Twain
7
Immutable
• Facts remain facts, and facts cannot be modified
• The fact that IBM Mark I was shipped in February
1944 remains an immutable fact
• If nothing in the functional program varies, the very
notion of variables becomes meaningless
• It is impossible to make a change in place when
doing FP (destruction is outlawed)
8
Isn’t that totally unrealistic?
• If it is impossible to make any destructive action
(such as mutating a value assigned to a variable)
when writing a functional program, how do we
account for the changes that occur in real life?
9
Example
• A customer applies for a loan in June 2014 and gets adjudicated with
Equifax credit score 690
• The same customer applies again for a loan 6 months later (in December
2014) and this time gets adjudicated with the score of 530
• Obviously, there’s been a real change
• How do we record that change using FP?
• We leave the old fact from June 2014 immutable
• We create a new fact that is valid for December 2014 (the only allowed
operation is production)
• Both facts characterize this customer
10
11
Mutability is Evil
• GOTO is evil because it makes us scratch our
heads “how did I get to this point of execution?”
• Mutability is evil because it makes us scratch our
heads “how did I get to this state?”
12
Programming Is About
Transforming Data
• We don’t hack existing data in place
• Instead, we always transform it into something new
• For example, we never capitalize a string, we return
a capitalized copy of a string
13
Performance Implications?
• At a first glance it may seem as if immutability is
inefficient (keep the old value and produce a new
value instead of simply overwriting the old value)
• Actually, the reverse is true — it improves efficiency
and performance
• FP uses lots and lots of processes, each with its
own heap and the data gets distributed among many
heaps, resulting in much faster garbage collection
14
What Are Functions?
• Binary relations that map arguments to results
• Pure functions simply return results and do not
produce any side effects
15
What Are Side Effects?
• Modifying a value in-place (i.e. mutating a variable)
• Modifying a data structure in-place
• Setting a field on an object
• Throwing an exception or halting with an error
• Printing to the console or reading user input
• Reading from or writing to a file
• Drawing on the screen
16
Ground Rules for FP
• Each and every function must accept at least one
argument
• Each and every function must return either a value
or another function
• No loops!
17
Switching from Imperative to
FP
• Any time we notice repetitious code, we notice a
candidate for a function
• The idea is to break it down to basic, atomic
functions that are doing one thing only
18
FP is Unit Tester’s Wet
Dream!
• Functions are idempotent (same as HTTP GET)
• Consequently, functions don’t have side effects
• It is impossible to modify a value in place (non-
destructive)
• It is also impossible to modify a value outside
function’s scope (non-destructive)
19
You Are Always Testing Only
One Thing
• The only volatile thing to test is the return value
• No need to worry whether we’re calling functions in the
right order
• No need to worry about whether we’re setting the
external state properly (no preconditions)
• In imperative languages (C++, C#, Java, Ruby, etc.)
checking the return value is not sufficient (imperative
programs may modify external state and thus result in
undesirable conditions)
20
Troubleshooter’s and
Debugger’s Wet Dream!
• Easy to reproduce the problem because it does not
depend on code that got executed before the bug
happened
• If a return value of a function is wrong, it is always
wrong! — the order of execution does not matter
(deterministic)
21
Hot Fix Deployer’s Wet
Dream!
• Impossible feat in the imperative world
• Unloading a class at runtime and reloading new
definition — every instance of that class will become
unusable (the state will be destroyed)
• In FP, because there is no state, all we have to do is
run a diff between code in prod and the new version
and then deploy the new code
22
Homoiconic
• There is no difference between source code and
data
• Parse source code the same way you’d parse your
data and then programmatically produce new useful
code during run time
• Metaprogramming
23
Bring ‘Soft’ Back Into Software
When you learn
this
Can you easily go back
and change
this?
24
Stop thinking in terms of
responsibilities and start thinking
in terms of getting things done
25
A Few Guidelines
• The foundations of programming are not assignments, if
statements and loops
• Concurrency does not need locks, semaphores, monitors
etc.
• Processes are not necessarily expensive resources
• Metaprogramming is not something tacked onto a language
• In FP, = is not an assignment operator, it can be viewed as
an assertion operator, and sometimes as a match operator
26
Higher Order Functions
• If we see that logic inside a function differs
depending on the context, we break it out into a
higher order function
27
Other FP Advantages
• Currying — throw away your GoF Design Patterns
book
• Lazy Evaluation
• Continuations
• Pattern matching
• Closures
• Monads
28

From Imperative to Functional Programming (for Absolute Beginners)

  • 1.
    From Imperative to FunctionalProgramming Alex Bunardzic, January 2015
  • 2.
    History of Computing •World War II — US Army & Navy artillery ballistics • Manual calculations not feasible • In February 1944 IBM delivered Automatic Sequence Controlled Calculator (ASCC), a.k.a. Mark I — weighed 5 tons, had 750,000 parts and could perform 3 operations per second 2
  • 3.
    Two Paradigms Alonzo Church Lambdacalculus (Declarative) Alan Turing Turing machine (Imperative) 3
  • 4.
    What’s the Difference? •Programming using declarative paradigm is like explaining your problem to a mathematician • Programming using imperative paradigm is like explaining your problem to an idiot • Granted, it is much easier to explain your problem to an idiot, because the idiot doesn’t have any opinions and will not push back 4
  • 5.
    Functional Paradigm • Setof ideas, not a set of strict guidelines • Deals with calculations (algebra) • Uses functions to do that • Doesn’t use variables • Doesn’t use assignments • No conditional statements • No loops 5
  • 6.
    FP Outlaws Destruction •Not possible to destroy anything within the FP world • The only possible thing is production 6
  • 7.
    Stateless • Ignorant ofthe past • Functional programs perform every task as if for the first time ever (idempotency) • Functional programs do not maintain state • “Good thing about telling the truth is that you don’t have to remember anything” — Mark Twain 7
  • 8.
    Immutable • Facts remainfacts, and facts cannot be modified • The fact that IBM Mark I was shipped in February 1944 remains an immutable fact • If nothing in the functional program varies, the very notion of variables becomes meaningless • It is impossible to make a change in place when doing FP (destruction is outlawed) 8
  • 9.
    Isn’t that totallyunrealistic? • If it is impossible to make any destructive action (such as mutating a value assigned to a variable) when writing a functional program, how do we account for the changes that occur in real life? 9
  • 10.
    Example • A customerapplies for a loan in June 2014 and gets adjudicated with Equifax credit score 690 • The same customer applies again for a loan 6 months later (in December 2014) and this time gets adjudicated with the score of 530 • Obviously, there’s been a real change • How do we record that change using FP? • We leave the old fact from June 2014 immutable • We create a new fact that is valid for December 2014 (the only allowed operation is production) • Both facts characterize this customer 10
  • 11.
  • 12.
    Mutability is Evil •GOTO is evil because it makes us scratch our heads “how did I get to this point of execution?” • Mutability is evil because it makes us scratch our heads “how did I get to this state?” 12
  • 13.
    Programming Is About TransformingData • We don’t hack existing data in place • Instead, we always transform it into something new • For example, we never capitalize a string, we return a capitalized copy of a string 13
  • 14.
    Performance Implications? • Ata first glance it may seem as if immutability is inefficient (keep the old value and produce a new value instead of simply overwriting the old value) • Actually, the reverse is true — it improves efficiency and performance • FP uses lots and lots of processes, each with its own heap and the data gets distributed among many heaps, resulting in much faster garbage collection 14
  • 15.
    What Are Functions? •Binary relations that map arguments to results • Pure functions simply return results and do not produce any side effects 15
  • 16.
    What Are SideEffects? • Modifying a value in-place (i.e. mutating a variable) • Modifying a data structure in-place • Setting a field on an object • Throwing an exception or halting with an error • Printing to the console or reading user input • Reading from or writing to a file • Drawing on the screen 16
  • 17.
    Ground Rules forFP • Each and every function must accept at least one argument • Each and every function must return either a value or another function • No loops! 17
  • 18.
    Switching from Imperativeto FP • Any time we notice repetitious code, we notice a candidate for a function • The idea is to break it down to basic, atomic functions that are doing one thing only 18
  • 19.
    FP is UnitTester’s Wet Dream! • Functions are idempotent (same as HTTP GET) • Consequently, functions don’t have side effects • It is impossible to modify a value in place (non- destructive) • It is also impossible to modify a value outside function’s scope (non-destructive) 19
  • 20.
    You Are AlwaysTesting Only One Thing • The only volatile thing to test is the return value • No need to worry whether we’re calling functions in the right order • No need to worry about whether we’re setting the external state properly (no preconditions) • In imperative languages (C++, C#, Java, Ruby, etc.) checking the return value is not sufficient (imperative programs may modify external state and thus result in undesirable conditions) 20
  • 21.
    Troubleshooter’s and Debugger’s WetDream! • Easy to reproduce the problem because it does not depend on code that got executed before the bug happened • If a return value of a function is wrong, it is always wrong! — the order of execution does not matter (deterministic) 21
  • 22.
    Hot Fix Deployer’sWet Dream! • Impossible feat in the imperative world • Unloading a class at runtime and reloading new definition — every instance of that class will become unusable (the state will be destroyed) • In FP, because there is no state, all we have to do is run a diff between code in prod and the new version and then deploy the new code 22
  • 23.
    Homoiconic • There isno difference between source code and data • Parse source code the same way you’d parse your data and then programmatically produce new useful code during run time • Metaprogramming 23
  • 24.
    Bring ‘Soft’ BackInto Software When you learn this Can you easily go back and change this? 24
  • 25.
    Stop thinking interms of responsibilities and start thinking in terms of getting things done 25
  • 26.
    A Few Guidelines •The foundations of programming are not assignments, if statements and loops • Concurrency does not need locks, semaphores, monitors etc. • Processes are not necessarily expensive resources • Metaprogramming is not something tacked onto a language • In FP, = is not an assignment operator, it can be viewed as an assertion operator, and sometimes as a match operator 26
  • 27.
    Higher Order Functions •If we see that logic inside a function differs depending on the context, we break it out into a higher order function 27
  • 28.
    Other FP Advantages •Currying — throw away your GoF Design Patterns book • Lazy Evaluation • Continuations • Pattern matching • Closures • Monads 28