291
Functional Programming with Immutable Data Structures Why Imperative Languages are Fundamentally Broken in a Multi-Threaded Environment Ivar Thorson Italian Institute of Technology November 2, 2010

Functional Programming with Immutable Data Structures

Embed Size (px)

DESCRIPTION

author: Ivar Thorsongreat slide!!! congratulations.

Citation preview

Page 1: Functional Programming with Immutable Data Structures

Functional Programming withImmutable Data Structures

Why Imperative Languages are

Fundamentally Broken in a

Multi-Threaded Environment

Ivar Thorson

Italian Institute of Technology

November 2, 2010

Page 2: Functional Programming with Immutable Data Structures

Ivar Thorson

Page 3: Functional Programming with Immutable Data Structures
Page 4: Functional Programming with Immutable Data Structures

Research interests:

Page 5: Functional Programming with Immutable Data Structures

Compliant actuation

Page 6: Functional Programming with Immutable Data Structures

Hopping Robots

Page 7: Functional Programming with Immutable Data Structures

Rigid Body Dynamics Simulations

Page 8: Functional Programming with Immutable Data Structures

The Next 37 minutes:

Page 9: Functional Programming with Immutable Data Structures

Important abstractions of functional

programming

Page 10: Functional Programming with Immutable Data Structures

particularly for a 4-year old language

Page 11: Functional Programming with Immutable Data Structures
Page 12: Functional Programming with Immutable Data Structures

Rich Hickey

Page 13: Functional Programming with Immutable Data Structures

What I have learned from his work

Page 14: Functional Programming with Immutable Data Structures

Clojure: Blending theoretical abstractions +

practical know-how

Page 15: Functional Programming with Immutable Data Structures

Target Audience: C, C++, Java, Matlab

Programmers

Page 16: Functional Programming with Immutable Data Structures

Tempting to start with a feature tour!

Page 17: Functional Programming with Immutable Data Structures

But you won’t understand why Clojure is

cool without context

Page 18: Functional Programming with Immutable Data Structures
Page 19: Functional Programming with Immutable Data Structures
Page 20: Functional Programming with Immutable Data Structures

Actually, I’m going to try to knock the cup

out of your hand.

Page 21: Functional Programming with Immutable Data Structures

Three Outdated Concepts

1. Variables

2. Syntax

3. Object Orientation

Page 22: Functional Programming with Immutable Data Structures

Three Outdated Concepts

1. Variables

2. Syntax

3. Object Orientation

Page 23: Functional Programming with Immutable Data Structures

Three Outdated Concepts

1. Variables

2. Syntax

3. Object Orientation

Page 24: Functional Programming with Immutable Data Structures

Three Outdated Concepts

1. Variables

2. Syntax

3. Object Orientation

Page 25: Functional Programming with Immutable Data Structures

Goal is to convince you that

1. shared mutable data is now a

philosophically bankrupt idea.

2. code and data should be structured as

trees

3. OOP isn’t the best way to achieve

OOP’s goals

Page 26: Functional Programming with Immutable Data Structures

Goal is to convince you that

1. shared mutable data is now a

philosophically bankrupt idea.

2. code and data should be structured as

trees

3. OOP isn’t the best way to achieve

OOP’s goals

Page 27: Functional Programming with Immutable Data Structures

Goal is to convince you that

1. shared mutable data is now a

philosophically bankrupt idea.

2. code and data should be structured as

trees

3. OOP isn’t the best way to achieve

OOP’s goals

Page 28: Functional Programming with Immutable Data Structures

Goal is to convince you that

1. shared mutable data is now a

philosophically bankrupt idea.

2. code and data should be structured as

trees

3. OOP isn’t the best way to achieve

OOP’s goals

Page 29: Functional Programming with Immutable Data Structures

Speaking bluntly

1. everything you know is wrong (15 min)

2. lisp parentheses are better than syntax

(10 min)

3. OOP inheritance sucks (5 min)

Page 30: Functional Programming with Immutable Data Structures

Speaking bluntly

1. everything you know is wrong (15 min)

2. lisp parentheses are better than syntax

(10 min)

3. OOP inheritance sucks (5 min)

Page 31: Functional Programming with Immutable Data Structures

Speaking bluntly

1. everything you know is wrong (15 min)

2. lisp parentheses are better than syntax

(10 min)

3. OOP inheritance sucks (5 min)

Page 32: Functional Programming with Immutable Data Structures

Speaking bluntly

1. everything you know is wrong (15 min)

2. lisp parentheses are better than syntax

(10 min)

3. OOP inheritance sucks (5 min)

Page 33: Functional Programming with Immutable Data Structures

disclaimer: some hyperbole in previous

statements

Page 34: Functional Programming with Immutable Data Structures

Oh noes, too many parentheses!

Page 35: Functional Programming with Immutable Data Structures

Good reasons for parentheses

1. Lisp is homoiconic

2. Parentheses uniquely define tree-shaped

computations

3. Parentheses enable structural editing

Page 36: Functional Programming with Immutable Data Structures

Good reasons for parentheses

1. Lisp is homoiconic

2. Parentheses uniquely define tree-shaped

computations

3. Parentheses enable structural editing

Page 37: Functional Programming with Immutable Data Structures

Good reasons for parentheses

1. Lisp is homoiconic

2. Parentheses uniquely define tree-shaped

computations

3. Parentheses enable structural editing

Page 38: Functional Programming with Immutable Data Structures

Good reasons for parentheses

1. Lisp is homoiconic

2. Parentheses uniquely define tree-shaped

computations

3. Parentheses enable structural editing

Page 39: Functional Programming with Immutable Data Structures

For now, please be patient

Page 40: Functional Programming with Immutable Data Structures

Introduction: Motivation for multi-threaded

programming

Page 41: Functional Programming with Immutable Data Structures

1. Last 40 years: Moore’s Law

2. “Transistor count will double every 2

years”

Page 42: Functional Programming with Immutable Data Structures

1. Last 40 years: Moore’s Law

2. “Transistor count will double every 2

years”

Page 43: Functional Programming with Immutable Data Structures

1. Last 40 years: Moore’s Law

2. “Transistor count will double every 2

years”

Page 44: Functional Programming with Immutable Data Structures

# of transistors ≈ CPU performance

Page 45: Functional Programming with Immutable Data Structures
Page 46: Functional Programming with Immutable Data Structures

Constraining physical relationship between

power density, swiching time, oxide thickness

Page 47: Functional Programming with Immutable Data Structures
Page 48: Functional Programming with Immutable Data Structures

The future of hardware is increasingly parallel

Page 49: Functional Programming with Immutable Data Structures

The future of software will be ruled by

Amdahl’s law

Page 50: Functional Programming with Immutable Data Structures
Page 51: Functional Programming with Immutable Data Structures

Some things are sequential: Two women

cannot have a baby in 4.5 months.

Page 52: Functional Programming with Immutable Data Structures

1. Dividing up work is already a hard

design task

2. Resource contention makes this problem

harder

Page 53: Functional Programming with Immutable Data Structures

1. Dividing up work is already a hard

design task

2. Resource contention makes this problem

harder

Page 54: Functional Programming with Immutable Data Structures

1. Dividing up work is already a hard

design task

2. Resource contention makes this problem

harder

Page 55: Functional Programming with Immutable Data Structures

Common multi-threaded bugs:

I Invalid state

I Race conditions

I Deadlocks

I Livelocks

I Resource starvation

Page 56: Functional Programming with Immutable Data Structures

Common multi-threaded bugs:

I Invalid state

I Race conditions

I Deadlocks

I Livelocks

I Resource starvation

Page 57: Functional Programming with Immutable Data Structures

Common multi-threaded bugs:

I Invalid state

I Race conditions

I Deadlocks

I Livelocks

I Resource starvation

Page 58: Functional Programming with Immutable Data Structures

Common multi-threaded bugs:

I Invalid state

I Race conditions

I Deadlocks

I Livelocks

I Resource starvation

Page 59: Functional Programming with Immutable Data Structures

Common multi-threaded bugs:

I Invalid state

I Race conditions

I Deadlocks

I Livelocks

I Resource starvation

Page 60: Functional Programming with Immutable Data Structures

Common multi-threaded bugs:

I Invalid state

I Race conditions

I Deadlocks

I Livelocks

I Resource starvation

Page 61: Functional Programming with Immutable Data Structures

What if most bugs were merely due to the

imperative programming model?

Page 62: Functional Programming with Immutable Data Structures

Part 1: The Functional Programming Style

Page 63: Functional Programming with Immutable Data Structures
Page 64: Functional Programming with Immutable Data Structures

Pure functions always return the same result

when they get the same input.

Page 65: Functional Programming with Immutable Data Structures

Pure functions don’t...

I ...look outside their box

I ...modify anything, anywhere

I ...print messages to the user

I ...write to disk

Page 66: Functional Programming with Immutable Data Structures

Pure functions don’t...

I ...look outside their box

I ...modify anything, anywhere

I ...print messages to the user

I ...write to disk

Page 67: Functional Programming with Immutable Data Structures

Pure functions don’t...

I ...look outside their box

I ...modify anything, anywhere

I ...print messages to the user

I ...write to disk

Page 68: Functional Programming with Immutable Data Structures

Pure functions don’t...

I ...look outside their box

I ...modify anything, anywhere

I ...print messages to the user

I ...write to disk

Page 69: Functional Programming with Immutable Data Structures

Pure functions don’t...

I ...look outside their box

I ...modify anything, anywhere

I ...print messages to the user

I ...write to disk

Page 70: Functional Programming with Immutable Data Structures

Pure functions have no side effects

Page 71: Functional Programming with Immutable Data Structures

Nothing would change if you ran the function

again – anywhere!

Page 72: Functional Programming with Immutable Data Structures

f (x) = x2 + 1

Page 73: Functional Programming with Immutable Data Structures

Pure functions just return a value, and do

nothing more.

Page 74: Functional Programming with Immutable Data Structures

Pure functions compose to other pure

functions

Page 75: Functional Programming with Immutable Data Structures
Page 76: Functional Programming with Immutable Data Structures

f (a, b, c) = (a + b)/(c ∗ 2)

Page 77: Functional Programming with Immutable Data Structures

Languages that emphasize the use of pure

functions are called functional languages

Page 78: Functional Programming with Immutable Data Structures

Imperative languages describe computation

in terms of changes to state.

Page 79: Functional Programming with Immutable Data Structures

C, C++, Java, and most engineering

languages are imperative.

Page 80: Functional Programming with Immutable Data Structures

Imperative languages describe memory

operations instead of purely functional

operations.

Page 81: Functional Programming with Immutable Data Structures
Page 82: Functional Programming with Immutable Data Structures

Imperative style: directly causing side effects

on memory.

Page 83: Functional Programming with Immutable Data Structures

The assignment operator changes

memory...often a side effect!

Page 84: Functional Programming with Immutable Data Structures

Could you write a C program...

I without any non-local variables?

I where = is only used for initialization?

Page 85: Functional Programming with Immutable Data Structures

Could you write a C program...

I without any non-local variables?

I where = is only used for initialization?

Page 86: Functional Programming with Immutable Data Structures

Could you write a C program...

I without any non-local variables?

I where = is only used for initialization?

Page 87: Functional Programming with Immutable Data Structures

Next: Variables are fundamentally a bad

abstraction in multithreaded environments.

Page 88: Functional Programming with Immutable Data Structures

Claim #1. Shared mutable data is now

philosophically bankrupt

Page 89: Functional Programming with Immutable Data Structures

I x = x + 1

I x = 3 (...last time I checked!)

I In my universe, 3 = 3 + 1 is never true

Page 90: Functional Programming with Immutable Data Structures

I x = x + 1

I x = 3 (...last time I checked!)

I In my universe, 3 = 3 + 1 is never true

Page 91: Functional Programming with Immutable Data Structures

I x = x + 1

I x = 3 (...last time I checked!)

I In my universe, 3 = 3 + 1 is never true

Page 92: Functional Programming with Immutable Data Structures

I x = x + 1

I x = 3 (...last time I checked!)

I In my universe, 3 = 3 + 1 is never true

Page 93: Functional Programming with Immutable Data Structures

The Big Problem: the concept of variables

encourage us to forget about time.

Page 94: Functional Programming with Immutable Data Structures

x [t] = x0

x [t + 1] = x [t] + 1

Page 95: Functional Programming with Immutable Data Structures

The value of x for a given t is immutable

and unchanging!

Page 96: Functional Programming with Immutable Data Structures

The Most Important Slide

I x is a name, an identity of a sequence of

values

I x has different values at different times

I The values of x are related by pure

functions

I In this case, by the increment function

Page 97: Functional Programming with Immutable Data Structures

The Most Important Slide

I x is a name, an identity of a sequence of

values

I x has different values at different times

I The values of x are related by pure

functions

I In this case, by the increment function

Page 98: Functional Programming with Immutable Data Structures

The Most Important Slide

I x is a name, an identity of a sequence of

values

I x has different values at different times

I The values of x are related by pure

functions

I In this case, by the increment function

Page 99: Functional Programming with Immutable Data Structures

The Most Important Slide

I x is a name, an identity of a sequence of

values

I x has different values at different times

I The values of x are related by pure

functions

I In this case, by the increment function

Page 100: Functional Programming with Immutable Data Structures

The Most Important Slide

I x is a name, an identity of a sequence of

values

I x has different values at different times

I The values of x are related by pure

functions

I In this case, by the increment function

Page 101: Functional Programming with Immutable Data Structures
Page 102: Functional Programming with Immutable Data Structures
Page 103: Functional Programming with Immutable Data Structures

The idea of a variable confuses identity and

the most current value!

Page 104: Functional Programming with Immutable Data Structures
Page 105: Functional Programming with Immutable Data Structures

Locking: a tactic for winning a battle.

Page 106: Functional Programming with Immutable Data Structures

What we need is a strategy to win the war.

Page 107: Functional Programming with Immutable Data Structures

“What if all data was immutable?” – Rich

Hickey (not the first one to ask this question)

Page 108: Functional Programming with Immutable Data Structures

Keeping Old Immutable Data

I x@(t=0) → 5

I x@(t=1) → 6

I x@(t=13) → 7

I x@(t=15) → 8

I ...

Page 109: Functional Programming with Immutable Data Structures

Keeping Old Immutable Data

I x@(t=0) → 5

I x@(t=1) → 6

I x@(t=13) → 7

I x@(t=15) → 8

I ...

Page 110: Functional Programming with Immutable Data Structures

Keeping Old Immutable Data

I x@(t=0) → 5

I x@(t=1) → 6

I x@(t=13) → 7

I x@(t=15) → 8

I ...

Page 111: Functional Programming with Immutable Data Structures

Keeping Old Immutable Data

I x@(t=0) → 5

I x@(t=1) → 6

I x@(t=13) → 7

I x@(t=15) → 8

I ...

Page 112: Functional Programming with Immutable Data Structures

Keeping Old Immutable Data

I x@(t=0) → 5

I x@(t=1) → 6

I x@(t=13) → 7

I x@(t=15) → 8

I ...

Page 113: Functional Programming with Immutable Data Structures

Keeping Old Immutable Data

I x@(t=0) → 5

I x@(t=1) → 6

I x@(t=13) → 7

I x@(t=15) → 8

I ...

Page 114: Functional Programming with Immutable Data Structures

I The old values of the data are kept and

indexed by time

I Data is immutable once created – we

cannot/will not change it!

I Values only destroyed when unneeded

Page 115: Functional Programming with Immutable Data Structures

I The old values of the data are kept and

indexed by time

I Data is immutable once created – we

cannot/will not change it!

I Values only destroyed when unneeded

Page 116: Functional Programming with Immutable Data Structures

I The old values of the data are kept and

indexed by time

I Data is immutable once created – we

cannot/will not change it!

I Values only destroyed when unneeded

Page 117: Functional Programming with Immutable Data Structures

I The old values of the data are kept and

indexed by time

I Data is immutable once created – we

cannot/will not change it!

I Values only destroyed when unneeded

Page 118: Functional Programming with Immutable Data Structures

Doesn’t keeping old copies of data consume

too much memory?

Page 119: Functional Programming with Immutable Data Structures

I (a b c) + d = (a b c d)

I What if the input and output shared

structure?

I Sharing structure is dangerous for

mutable data

I ...but sharing structure is safe if the

data is immutable.

Page 120: Functional Programming with Immutable Data Structures

I (a b c) + d = (a b c d)

I What if the input and output shared

structure?

I Sharing structure is dangerous for

mutable data

I ...but sharing structure is safe if the

data is immutable.

Page 121: Functional Programming with Immutable Data Structures

I (a b c) + d = (a b c d)

I What if the input and output shared

structure?

I Sharing structure is dangerous for

mutable data

I ...but sharing structure is safe if the

data is immutable.

Page 122: Functional Programming with Immutable Data Structures

I (a b c) + d = (a b c d)

I What if the input and output shared

structure?

I Sharing structure is dangerous for

mutable data

I ...but sharing structure is safe if the

data is immutable.

Page 123: Functional Programming with Immutable Data Structures

I (a b c) + d = (a b c d)

I What if the input and output shared

structure?

I Sharing structure is dangerous for

mutable data

I ...but sharing structure is safe if the

data is immutable.

Page 124: Functional Programming with Immutable Data Structures

The Trick: Represent the list as a tree

Page 125: Functional Programming with Immutable Data Structures

input tree → pure function → output tree

Page 126: Functional Programming with Immutable Data Structures
Page 127: Functional Programming with Immutable Data Structures

both trees are immutable but distinct

Page 128: Functional Programming with Immutable Data Structures

Same approach works also for insertions,

modifications, deletions, and all other list

operations.

Page 129: Functional Programming with Immutable Data Structures

a million threads, a million trees, a million

references to trees, zero locks

Page 130: Functional Programming with Immutable Data Structures

If you want a more current worldview, just

get its reference

Page 131: Functional Programming with Immutable Data Structures

Advantages of immutable trees:

I No locking required

I No ’stopping the world’ to see (readers

don’t block writers)

I Worldview never becomes corrupted

I Minimizes memory use while

maintaining multiple copies

I Unused nodes are garbage-collected

Page 132: Functional Programming with Immutable Data Structures

Advantages of immutable trees:

I No locking required

I No ’stopping the world’ to see (readers

don’t block writers)

I Worldview never becomes corrupted

I Minimizes memory use while

maintaining multiple copies

I Unused nodes are garbage-collected

Page 133: Functional Programming with Immutable Data Structures

Advantages of immutable trees:

I No locking required

I No ’stopping the world’ to see (readers

don’t block writers)

I Worldview never becomes corrupted

I Minimizes memory use while

maintaining multiple copies

I Unused nodes are garbage-collected

Page 134: Functional Programming with Immutable Data Structures

Advantages of immutable trees:

I No locking required

I No ’stopping the world’ to see (readers

don’t block writers)

I Worldview never becomes corrupted

I Minimizes memory use while

maintaining multiple copies

I Unused nodes are garbage-collected

Page 135: Functional Programming with Immutable Data Structures

Advantages of immutable trees:

I No locking required

I No ’stopping the world’ to see (readers

don’t block writers)

I Worldview never becomes corrupted

I Minimizes memory use while

maintaining multiple copies

I Unused nodes are garbage-collected

Page 136: Functional Programming with Immutable Data Structures

Advantages of immutable trees:

I No locking required

I No ’stopping the world’ to see (readers

don’t block writers)

I Worldview never becomes corrupted

I Minimizes memory use while

maintaining multiple copies

I Unused nodes are garbage-collected

Page 137: Functional Programming with Immutable Data Structures

We’ve gone a long way, but we’re only half

way to real concurrency

Page 138: Functional Programming with Immutable Data Structures
Page 139: Functional Programming with Immutable Data Structures

Immutability lets us read concurrently, but

not write concurrently to a single piece of

data

Page 140: Functional Programming with Immutable Data Structures
Page 141: Functional Programming with Immutable Data Structures
Page 142: Functional Programming with Immutable Data Structures

How can we coordinate the actions of

different threads working on the same data

at the same time?

Page 143: Functional Programming with Immutable Data Structures

”Treat changes in an identity’s value as a

database transaction.” – Rich Hickey

Page 144: Functional Programming with Immutable Data Structures

Database Details:

I Software Transactional Memory (STM)

I Multi-Version Concurrency Control

(MVCC)

Page 145: Functional Programming with Immutable Data Structures

Database Details:

I Software Transactional Memory (STM)

I Multi-Version Concurrency Control

(MVCC)

Page 146: Functional Programming with Immutable Data Structures

Database Details:

I Software Transactional Memory (STM)

I Multi-Version Concurrency Control

(MVCC)

Page 147: Functional Programming with Immutable Data Structures

The STM Guarantees:

I Atomicity (All or nothing)

I Consistency (Validation before commits)

I Isolation (Transactions can’t see each

other)

Page 148: Functional Programming with Immutable Data Structures

The STM Guarantees:

I Atomicity (All or nothing)

I Consistency (Validation before commits)

I Isolation (Transactions can’t see each

other)

Page 149: Functional Programming with Immutable Data Structures

The STM Guarantees:

I Atomicity (All or nothing)

I Consistency (Validation before commits)

I Isolation (Transactions can’t see each

other)

Page 150: Functional Programming with Immutable Data Structures

The STM Guarantees:

I Atomicity (All or nothing)

I Consistency (Validation before commits)

I Isolation (Transactions can’t see each

other)

Page 151: Functional Programming with Immutable Data Structures
Page 152: Functional Programming with Immutable Data Structures

Transactions are speculative and may be

retried if there is a collision.

Page 153: Functional Programming with Immutable Data Structures

For even more concurrency:

I Sometimes you don’t care about the

order of function application

I Commutative writers won’t need to retry

I Writers don’t interfere with other

writers!

Page 154: Functional Programming with Immutable Data Structures

For even more concurrency:

I Sometimes you don’t care about the

order of function application

I Commutative writers won’t need to retry

I Writers don’t interfere with other

writers!

Page 155: Functional Programming with Immutable Data Structures

For even more concurrency:

I Sometimes you don’t care about the

order of function application

I Commutative writers won’t need to retry

I Writers don’t interfere with other

writers!

Page 156: Functional Programming with Immutable Data Structures

For even more concurrency:

I Sometimes you don’t care about the

order of function application

I Commutative writers won’t need to retry

I Writers don’t interfere with other

writers!

Page 157: Functional Programming with Immutable Data Structures

I STMs exist for other languages...

I ... but Clojure is first to have built-in

STM with pervasive immutability

Page 158: Functional Programming with Immutable Data Structures

I STMs exist for other languages...

I ... but Clojure is first to have built-in

STM with pervasive immutability

Page 159: Functional Programming with Immutable Data Structures

I STMs exist for other languages...

I ... but Clojure is first to have built-in

STM with pervasive immutability

Page 160: Functional Programming with Immutable Data Structures

Part 1 Summary: In Clojure...

I ...Readers don’t block anybody

I ...Writers don’t block anybody

I ...Writers retry if conflicting

I ...Writers don’t retry if commutative

Page 161: Functional Programming with Immutable Data Structures

Part 1 Summary: In Clojure...

I ...Readers don’t block anybody

I ...Writers don’t block anybody

I ...Writers retry if conflicting

I ...Writers don’t retry if commutative

Page 162: Functional Programming with Immutable Data Structures

Part 1 Summary: In Clojure...

I ...Readers don’t block anybody

I ...Writers don’t block anybody

I ...Writers retry if conflicting

I ...Writers don’t retry if commutative

Page 163: Functional Programming with Immutable Data Structures

Part 1 Summary: In Clojure...

I ...Readers don’t block anybody

I ...Writers don’t block anybody

I ...Writers retry if conflicting

I ...Writers don’t retry if commutative

Page 164: Functional Programming with Immutable Data Structures

Part 1 Summary: In Clojure...

I ...Readers don’t block anybody

I ...Writers don’t block anybody

I ...Writers retry if conflicting

I ...Writers don’t retry if commutative

Page 165: Functional Programming with Immutable Data Structures

Variables couldn’t do this because:

I Confuse identity and values

I Are mutable and can be corrupted

I Assume a single thread of control, no

interruptions

I Maintain only the last written copy

Page 166: Functional Programming with Immutable Data Structures

Variables couldn’t do this because:

I Confuse identity and values

I Are mutable and can be corrupted

I Assume a single thread of control, no

interruptions

I Maintain only the last written copy

Page 167: Functional Programming with Immutable Data Structures

Variables couldn’t do this because:

I Confuse identity and values

I Are mutable and can be corrupted

I Assume a single thread of control, no

interruptions

I Maintain only the last written copy

Page 168: Functional Programming with Immutable Data Structures

Variables couldn’t do this because:

I Confuse identity and values

I Are mutable and can be corrupted

I Assume a single thread of control, no

interruptions

I Maintain only the last written copy

Page 169: Functional Programming with Immutable Data Structures

Variables couldn’t do this because:

I Confuse identity and values

I Are mutable and can be corrupted

I Assume a single thread of control, no

interruptions

I Maintain only the last written copy

Page 170: Functional Programming with Immutable Data Structures

”Mutable stateful objects are the new

spaghetti code” – Rich Hickey

Page 171: Functional Programming with Immutable Data Structures

”We oppose the uncontrolled mutation of

variables.” – Stuart Halloway

Page 172: Functional Programming with Immutable Data Structures

”Mutable objects are a concurrency

disaster.” – Rich Hickey

Page 173: Functional Programming with Immutable Data Structures

”The future is a function of the past, but

doesn’t change it.” – Rich Hickey

Page 174: Functional Programming with Immutable Data Structures

”Many people can watch a baseball game,

but only one can be at bat.” – Rich Hickey

Page 175: Functional Programming with Immutable Data Structures

Part 2: Revenge of the Lisp

Page 176: Functional Programming with Immutable Data Structures

Claim #2: Your language’s syntax is

unneccesarily complex

Page 177: Functional Programming with Immutable Data Structures

Now we’ll explain why lisp has parentheses!

Page 178: Functional Programming with Immutable Data Structures
Page 179: Functional Programming with Immutable Data Structures

Pure functions represent computation as

trees

Page 180: Functional Programming with Immutable Data Structures

Reason 1: The tree structure is made

explicitly visible by the parentheses

Page 181: Functional Programming with Immutable Data Structures

Sorry, Haskell/Erlang/OCaml/ML/etc!

Page 182: Functional Programming with Immutable Data Structures

Infix Notation

1 + 1

Page 183: Functional Programming with Immutable Data Structures

Prefix Notation

(+ 1 1)

Page 184: Functional Programming with Immutable Data Structures

(fn arg1 arg2 arg3 ...)

Page 185: Functional Programming with Immutable Data Structures

1 + 2 + 3 + 4

Page 186: Functional Programming with Immutable Data Structures

(+ 1 2 3 4)

Page 187: Functional Programming with Immutable Data Structures

With prefix notation, you can forget about

the rules of precedence.

Page 188: Functional Programming with Immutable Data Structures

6 + 12 / 2 * 3

Page 189: Functional Programming with Immutable Data Structures

(6 + 12) / (2 * 3)

Page 190: Functional Programming with Immutable Data Structures

(/ (+ 6 12) (* 2 3))

Page 191: Functional Programming with Immutable Data Structures

(/ (+ 6p

12)

(* 2

3))

Page 192: Functional Programming with Immutable Data Structures

Triangular Tree Structure

Page 193: Functional Programming with Immutable Data Structures
Page 194: Functional Programming with Immutable Data Structures

Lisp code’s tree of computation is

exceptionally visible and regular.

Page 195: Functional Programming with Immutable Data Structures

Reason 2: Homoiconicity

Page 196: Functional Programming with Immutable Data Structures

Homoiconic = Homo + icon = ”same” +

”representation”

Page 197: Functional Programming with Immutable Data Structures

The property where code & a language

primitive look the same.

Page 198: Functional Programming with Immutable Data Structures

An example: Writing C with XML

Page 199: Functional Programming with Immutable Data Structures

for (i=0; i<100; i++) {

printf("%d\n", i);

dostuff();

}

Page 200: Functional Programming with Immutable Data Structures

<for>

<init>i = 0</init>

<test>i < 100</test>

<count>i++</count>

<body>

<print format="%d" args="i"/>

<dostuff/>

</body>

</for>

Page 201: Functional Programming with Immutable Data Structures

Imagine how simple it would be to use an

XML generator to emit compilable source

code.

Page 202: Functional Programming with Immutable Data Structures

We could modify our code programmatically.

Page 203: Functional Programming with Immutable Data Structures

In lisp, you can write programs that write

programs.

Page 204: Functional Programming with Immutable Data Structures

(list 1 2 3) -> (1 2 3)

Page 205: Functional Programming with Immutable Data Structures

(list ’+ 1 2 3) -> (+ 1 2 3)

(+ 1 2 3) -> 6

Page 206: Functional Programming with Immutable Data Structures

(defmacro and

([] true)

([x] x)

([x & rest]

‘(let [and# ~x]

(if and# (and ~@rest) and#))))

Page 207: Functional Programming with Immutable Data Structures

Why lispers go nuts:

I Macros in lisp are far more powerful

than in other languages.

I You can build new constructs that are

just as legitimate as existing constructs

like if

I You can abstract away boilerplate code

Page 208: Functional Programming with Immutable Data Structures

Why lispers go nuts:

I Macros in lisp are far more powerful

than in other languages.

I You can build new constructs that are

just as legitimate as existing constructs

like if

I You can abstract away boilerplate code

Page 209: Functional Programming with Immutable Data Structures

Why lispers go nuts:

I Macros in lisp are far more powerful

than in other languages.

I You can build new constructs that are

just as legitimate as existing constructs

like if

I You can abstract away boilerplate code

Page 210: Functional Programming with Immutable Data Structures

Why lispers go nuts:

I Macros in lisp are far more powerful

than in other languages.

I You can build new constructs that are

just as legitimate as existing constructs

like if

I You can abstract away boilerplate code

Page 211: Functional Programming with Immutable Data Structures

Aside

I If Java used parentheses properly, XML

wouldn’t exist

I Lisp parentheses describe structure

I Most languages use ad-hoc syntax, data

formats

I Simplicity is elegance

Page 212: Functional Programming with Immutable Data Structures

Aside

I If Java used parentheses properly, XML

wouldn’t exist

I Lisp parentheses describe structure

I Most languages use ad-hoc syntax, data

formats

I Simplicity is elegance

Page 213: Functional Programming with Immutable Data Structures

Aside

I If Java used parentheses properly, XML

wouldn’t exist

I Lisp parentheses describe structure

I Most languages use ad-hoc syntax, data

formats

I Simplicity is elegance

Page 214: Functional Programming with Immutable Data Structures

Aside

I If Java used parentheses properly, XML

wouldn’t exist

I Lisp parentheses describe structure

I Most languages use ad-hoc syntax, data

formats

I Simplicity is elegance

Page 215: Functional Programming with Immutable Data Structures

Aside

I If Java used parentheses properly, XML

wouldn’t exist

I Lisp parentheses describe structure

I Most languages use ad-hoc syntax, data

formats

I Simplicity is elegance

Page 216: Functional Programming with Immutable Data Structures

Reason 3: Structural Editing

Page 217: Functional Programming with Immutable Data Structures

Good editors let you work with code in

blocks and forget about the parentheses.

Page 218: Functional Programming with Immutable Data Structures

Hard-to-show Examples

I When you type (, emacs adds the )

I Indentation is automatic

I You can easily navigate heirarchically

I Take next three expressions, apply them

to a function

Page 219: Functional Programming with Immutable Data Structures

Hard-to-show Examples

I When you type (, emacs adds the )

I Indentation is automatic

I You can easily navigate heirarchically

I Take next three expressions, apply them

to a function

Page 220: Functional Programming with Immutable Data Structures

Hard-to-show Examples

I When you type (, emacs adds the )

I Indentation is automatic

I You can easily navigate heirarchically

I Take next three expressions, apply them

to a function

Page 221: Functional Programming with Immutable Data Structures

Hard-to-show Examples

I When you type (, emacs adds the )

I Indentation is automatic

I You can easily navigate heirarchically

I Take next three expressions, apply them

to a function

Page 222: Functional Programming with Immutable Data Structures

Hard-to-show Examples

I When you type (, emacs adds the )

I Indentation is automatic

I You can easily navigate heirarchically

I Take next three expressions, apply them

to a function

Page 223: Functional Programming with Immutable Data Structures

Summary of Lisp Parentheses

I Parentheses render explicit the

tree-structure of your program

I Homoiconicity lets you write programs

with programs

I Structural Editing is fun and easy

Page 224: Functional Programming with Immutable Data Structures

Summary of Lisp Parentheses

I Parentheses render explicit the

tree-structure of your program

I Homoiconicity lets you write programs

with programs

I Structural Editing is fun and easy

Page 225: Functional Programming with Immutable Data Structures

Summary of Lisp Parentheses

I Parentheses render explicit the

tree-structure of your program

I Homoiconicity lets you write programs

with programs

I Structural Editing is fun and easy

Page 226: Functional Programming with Immutable Data Structures

Summary of Lisp Parentheses

I Parentheses render explicit the

tree-structure of your program

I Homoiconicity lets you write programs

with programs

I Structural Editing is fun and easy

Page 227: Functional Programming with Immutable Data Structures

Syntax is bad because

I It hides the program’s structure

I It destroys homoiconicity

I It is needlessly complex

Page 228: Functional Programming with Immutable Data Structures

Syntax is bad because

I It hides the program’s structure

I It destroys homoiconicity

I It is needlessly complex

Page 229: Functional Programming with Immutable Data Structures

Syntax is bad because

I It hides the program’s structure

I It destroys homoiconicity

I It is needlessly complex

Page 230: Functional Programming with Immutable Data Structures

Syntax is bad because

I It hides the program’s structure

I It destroys homoiconicity

I It is needlessly complex

Page 231: Functional Programming with Immutable Data Structures

”Things should be made as simple as

possible – but no simpler.” – Albert Einstein

Page 232: Functional Programming with Immutable Data Structures

Part 3: OOP isn’t the only path to

Polymorphism and Code Reuse

Page 233: Functional Programming with Immutable Data Structures

OOP has good goals

1. to group objects together

2. to encapsulate

3. to dispatch polymorphically

4. to reuse code

Page 234: Functional Programming with Immutable Data Structures

OOP has good goals

1. to group objects together

2. to encapsulate

3. to dispatch polymorphically

4. to reuse code

Page 235: Functional Programming with Immutable Data Structures

OOP has good goals

1. to group objects together

2. to encapsulate

3. to dispatch polymorphically

4. to reuse code

Page 236: Functional Programming with Immutable Data Structures

OOP has good goals

1. to group objects together

2. to encapsulate

3. to dispatch polymorphically

4. to reuse code

Page 237: Functional Programming with Immutable Data Structures

OOP has good goals

1. to group objects together

2. to encapsulate

3. to dispatch polymorphically

4. to reuse code

Page 238: Functional Programming with Immutable Data Structures

These are all good ideas and good goals.

Page 239: Functional Programming with Immutable Data Structures

However, OOP is not the only way to reach

these goals.

Page 240: Functional Programming with Immutable Data Structures

Claim #3: ”Functions compose better than

objects.”

Page 241: Functional Programming with Immutable Data Structures

The fundamental mechanism of OOP – the

inheritance of data, interfaces, type, or

methods from a parent – is often more

difficult to use in practice than techniques

that use functions to achieve the same effect.

Page 242: Functional Programming with Immutable Data Structures

Functions are simpler than objects.

Page 243: Functional Programming with Immutable Data Structures

Objects are semantic compounds of types,

data, and methods.

Page 244: Functional Programming with Immutable Data Structures

Implementation inheritance is bad:

I Forces “is-a” relationship instead of

“has-a”, and “has-a” is almost always

better

I Heirarchical nominalization is difficult

I Changes to a class affect all the

subclasses

Page 245: Functional Programming with Immutable Data Structures

Implementation inheritance is bad:

I Forces “is-a” relationship instead of

“has-a”, and “has-a” is almost always

better

I Heirarchical nominalization is difficult

I Changes to a class affect all the

subclasses

Page 246: Functional Programming with Immutable Data Structures

Implementation inheritance is bad:

I Forces “is-a” relationship instead of

“has-a”, and “has-a” is almost always

better

I Heirarchical nominalization is difficult

I Changes to a class affect all the

subclasses

Page 247: Functional Programming with Immutable Data Structures

Implementation inheritance is bad:

I Forces “is-a” relationship instead of

“has-a”, and “has-a” is almost always

better

I Heirarchical nominalization is difficult

I Changes to a class affect all the

subclasses

Page 248: Functional Programming with Immutable Data Structures

An example will help clarify.

Page 249: Functional Programming with Immutable Data Structures

Balls

I Ball class (presumably round)

I rollingBall subclass

I bouncingBall subclass

Page 250: Functional Programming with Immutable Data Structures

Balls

I Ball class (presumably round)

I rollingBall subclass

I bouncingBall subclass

Page 251: Functional Programming with Immutable Data Structures

Balls

I Ball class (presumably round)

I rollingBall subclass

I bouncingBall subclass

Page 252: Functional Programming with Immutable Data Structures

Balls

I Ball class (presumably round)

I rollingBall subclass

I bouncingBall subclass

Page 253: Functional Programming with Immutable Data Structures

Problems

I What happens if we want to make a ball

that both rolls and bounces?

I Do/Can we inherit from both?

I What if our ball cracks and loses its

bounciness?

I Is a non-round rugby ball a subclass of

ball too?

Page 254: Functional Programming with Immutable Data Structures

Problems

I What happens if we want to make a ball

that both rolls and bounces?

I Do/Can we inherit from both?

I What if our ball cracks and loses its

bounciness?

I Is a non-round rugby ball a subclass of

ball too?

Page 255: Functional Programming with Immutable Data Structures

Problems

I What happens if we want to make a ball

that both rolls and bounces?

I Do/Can we inherit from both?

I What if our ball cracks and loses its

bounciness?

I Is a non-round rugby ball a subclass of

ball too?

Page 256: Functional Programming with Immutable Data Structures

Problems

I What happens if we want to make a ball

that both rolls and bounces?

I Do/Can we inherit from both?

I What if our ball cracks and loses its

bounciness?

I Is a non-round rugby ball a subclass of

ball too?

Page 257: Functional Programming with Immutable Data Structures

Problems

I What happens if we want to make a ball

that both rolls and bounces?

I Do/Can we inherit from both?

I What if our ball cracks and loses its

bounciness?

I Is a non-round rugby ball a subclass of

ball too?

Page 258: Functional Programming with Immutable Data Structures

Interfaces are Simpler

I Define functional interfaces, but don’t

inherit the implementation

I If you want to use another object’s

function to accomplish a task, just use it

I No need to encapsulate their function in

an object

I Multiple interfaces are simpler than

multiple inheritance

Page 259: Functional Programming with Immutable Data Structures

Interfaces are Simpler

I Define functional interfaces, but don’t

inherit the implementation

I If you want to use another object’s

function to accomplish a task, just use it

I No need to encapsulate their function in

an object

I Multiple interfaces are simpler than

multiple inheritance

Page 260: Functional Programming with Immutable Data Structures

Interfaces are Simpler

I Define functional interfaces, but don’t

inherit the implementation

I If you want to use another object’s

function to accomplish a task, just use it

I No need to encapsulate their function in

an object

I Multiple interfaces are simpler than

multiple inheritance

Page 261: Functional Programming with Immutable Data Structures

Interfaces are Simpler

I Define functional interfaces, but don’t

inherit the implementation

I If you want to use another object’s

function to accomplish a task, just use it

I No need to encapsulate their function in

an object

I Multiple interfaces are simpler than

multiple inheritance

Page 262: Functional Programming with Immutable Data Structures

Interfaces are Simpler

I Define functional interfaces, but don’t

inherit the implementation

I If you want to use another object’s

function to accomplish a task, just use it

I No need to encapsulate their function in

an object

I Multiple interfaces are simpler than

multiple inheritance

Page 263: Functional Programming with Immutable Data Structures

FREE THE VERBS!! Separate your object

methods from your objects!

Page 264: Functional Programming with Immutable Data Structures

Example: Single vs Multiple Dispatch

Page 265: Functional Programming with Immutable Data Structures

Making Drum Noises

I Drum, cymbal and stick classes

I When I hit something with the stick, it

makes a noise

I Single Dispatch:

drum.makeNoise(drumstick)

I cymbal.makeNoise(drumstick)

Page 266: Functional Programming with Immutable Data Structures

Making Drum Noises

I Drum, cymbal and stick classes

I When I hit something with the stick, it

makes a noise

I Single Dispatch:

drum.makeNoise(drumstick)

I cymbal.makeNoise(drumstick)

Page 267: Functional Programming with Immutable Data Structures

Making Drum Noises

I Drum, cymbal and stick classes

I When I hit something with the stick, it

makes a noise

I Single Dispatch:

drum.makeNoise(drumstick)

I cymbal.makeNoise(drumstick)

Page 268: Functional Programming with Immutable Data Structures

Making Drum Noises

I Drum, cymbal and stick classes

I When I hit something with the stick, it

makes a noise

I Single Dispatch:

drum.makeNoise(drumstick)

I cymbal.makeNoise(drumstick)

Page 269: Functional Programming with Immutable Data Structures

Making Drum Noises

I Drum, cymbal and stick classes

I When I hit something with the stick, it

makes a noise

I Single Dispatch:

drum.makeNoise(drumstick)

I cymbal.makeNoise(drumstick)

Page 270: Functional Programming with Immutable Data Structures

The verbs are owned by the nouns.

Page 271: Functional Programming with Immutable Data Structures

But what happens when I add a different

stick class?

Page 272: Functional Programming with Immutable Data Structures
Page 273: Functional Programming with Immutable Data Structures
Page 274: Functional Programming with Immutable Data Structures

Now I will need to modify the drum and

cymbal classes and add new methods to

handle the mallets!

Page 275: Functional Programming with Immutable Data Structures

When two objects hit, the sound is function

of both objects.

Page 276: Functional Programming with Immutable Data Structures

With multi-method functions

I hit(drumstick, cymbal) = crash

I hit(mallet, cymbal) = roar

I hit(drumstick, drum) = bam

I hit(mallet, drum) = bom

I hit(drumstick, drumstick) = click

I hit(cymbal, cymbal) = loud crash

Page 277: Functional Programming with Immutable Data Structures

With multi-method functions

I hit(drumstick, cymbal) = crash

I hit(mallet, cymbal) = roar

I hit(drumstick, drum) = bam

I hit(mallet, drum) = bom

I hit(drumstick, drumstick) = click

I hit(cymbal, cymbal) = loud crash

Page 278: Functional Programming with Immutable Data Structures

With multi-method functions

I hit(drumstick, cymbal) = crash

I hit(mallet, cymbal) = roar

I hit(drumstick, drum) = bam

I hit(mallet, drum) = bom

I hit(drumstick, drumstick) = click

I hit(cymbal, cymbal) = loud crash

Page 279: Functional Programming with Immutable Data Structures

With multi-method functions

I hit(drumstick, cymbal) = crash

I hit(mallet, cymbal) = roar

I hit(drumstick, drum) = bam

I hit(mallet, drum) = bom

I hit(drumstick, drumstick) = click

I hit(cymbal, cymbal) = loud crash

Page 280: Functional Programming with Immutable Data Structures

With multi-method functions

I hit(drumstick, cymbal) = crash

I hit(mallet, cymbal) = roar

I hit(drumstick, drum) = bam

I hit(mallet, drum) = bom

I hit(drumstick, drumstick) = click

I hit(cymbal, cymbal) = loud crash

Page 281: Functional Programming with Immutable Data Structures

With multi-method functions

I hit(drumstick, cymbal) = crash

I hit(mallet, cymbal) = roar

I hit(drumstick, drum) = bam

I hit(mallet, drum) = bom

I hit(drumstick, drumstick) = click

I hit(cymbal, cymbal) = loud crash

Page 282: Functional Programming with Immutable Data Structures

With multi-method functions

I hit(drumstick, cymbal) = crash

I hit(mallet, cymbal) = roar

I hit(drumstick, drum) = bam

I hit(mallet, drum) = bom

I hit(drumstick, drumstick) = click

I hit(cymbal, cymbal) = loud crash

Page 283: Functional Programming with Immutable Data Structures

IMPORTANT: hit() is not a single function,

but a collection of functions. (It is called a

multi-method or generic function)

Page 284: Functional Programming with Immutable Data Structures

The particular function that is called is

determined by the type of both of its

arguments.

Page 285: Functional Programming with Immutable Data Structures

As you add more classes, just add more

definitions of hit().

Page 286: Functional Programming with Immutable Data Structures

Part 3 Conclusion

I Polymorphism is better done through

interfaces than subtype inheritance.

I Functions do not require a heirarchy

I Functions allow simple multiple dispatch

Page 287: Functional Programming with Immutable Data Structures

Part 3 Conclusion

I Polymorphism is better done through

interfaces than subtype inheritance.

I Functions do not require a heirarchy

I Functions allow simple multiple dispatch

Page 288: Functional Programming with Immutable Data Structures

Part 3 Conclusion

I Polymorphism is better done through

interfaces than subtype inheritance.

I Functions do not require a heirarchy

I Functions allow simple multiple dispatch

Page 289: Functional Programming with Immutable Data Structures

Part 3 Conclusion

I Polymorphism is better done through

interfaces than subtype inheritance.

I Functions do not require a heirarchy

I Functions allow simple multiple dispatch

Page 290: Functional Programming with Immutable Data Structures

The End

Page 291: Functional Programming with Immutable Data Structures

Any Questions?