from imperative to functional programming (for absolute beginners)

28
From Imperative to Functional Programming Alex Bunardzic, January 2015

Upload: alex-bunardzic

Post on 24-Jul-2015

125 views

Category:

Software


1 download

TRANSCRIPT

From Imperative to Functional

ProgrammingAlex 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

Two Paradigms

Alonzo ChurchLambda calculus

(Declarative)

Alan TuringTuring machine

(Imperative)

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

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

FP Outlaws Destruction

• Not possible to destroy anything within the FP world

• The only possible thing is production

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

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)

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?

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

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?”

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

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

What Are Functions?

• Binary relations that map arguments to results

• Pure functions simply return results and do not produce any side effects

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

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!

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

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)

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)

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)

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

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

Bring ‘Soft’ Back Into Software

When you learnthis

Can you easily go backand change

this?

Stop thinking in terms of responsibilities and start

thinking in terms of getting things done

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

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

Other FP Advantages• Currying — throw away your GoF Design

Patterns book

• Lazy Evaluation

• Continuations

• Pattern matching

• Closures

• Monads