Introduction to Functional Programming

Preview:

Citation preview

An Introduction to Functional Programming

Andreas Pauley – @apauley

Pattern Matched TechnologiesLambda Luminaries @lambdaluminary

September 2, 2013

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 1 / 58

Pattern Matched Technologies

Developing financial applications in Erlang.http://www.patternmatched.com/

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 2 / 58

Lambda Luminaries – @lambdaluminaryLocal functional programming user group

We meet once a month, on the second Monday of the month.http://www.meetup.com/lambda-luminaries/

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 3 / 58

Introduction

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 4 / 58

Introduction

A word from the wise

“ No matter what language you work in, programming ina functional style provides benefits. You should do itwhenever it is convenient, and you should think hardabout the decision when it isn’t convenient. ”

— John Carmack, ID Software [2]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 5 / 58

Introduction

Quake

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 6 / 58

Introduction

A Few Functional Programming Languages

Haskell Strong focus on functional purity. Lazy evaluation.Advanced static type system. Native-code compiler.

Erlang Focused around concurrency and distributed programming.Strict evaluation. Dynamic typing. Runs on the BEAM VM.

Clojure A modern Lisp language. Focus on concurrency. Lazyevaluation. Dynamic typing. Runs on the JVM.

Scala FP and OO. Strict evaluation by default, but supports lazyevaluation. Advanced static type system. Runs on the JVM.

OCaml FP and OO. Part of the ML family. Sometimes claimed tobe “faster than C”. Strict evaluation. Advanced static typesystem. Native-code compiler.

F# FP and OO. Based on OCaml. Strict evaluation by default,but supports lazy evaluation. Advanced static type system.Runs on the .NET CLR.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 7 / 58

Introduction

A Few Functional Programming Languages

Haskell Strong focus on functional purity. Lazy evaluation.Advanced static type system. Native-code compiler.

Erlang Focused around concurrency and distributed programming.Strict evaluation. Dynamic typing. Runs on the BEAM VM.

Clojure A modern Lisp language. Focus on concurrency. Lazyevaluation. Dynamic typing. Runs on the JVM.

Scala FP and OO. Strict evaluation by default, but supports lazyevaluation. Advanced static type system. Runs on the JVM.

OCaml FP and OO. Part of the ML family. Sometimes claimed tobe “faster than C”. Strict evaluation. Advanced static typesystem. Native-code compiler.

F# FP and OO. Based on OCaml. Strict evaluation by default,but supports lazy evaluation. Advanced static type system.Runs on the .NET CLR.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 7 / 58

Introduction

A Few Functional Programming Languages

Haskell Strong focus on functional purity. Lazy evaluation.Advanced static type system. Native-code compiler.

Erlang Focused around concurrency and distributed programming.Strict evaluation. Dynamic typing. Runs on the BEAM VM.

Clojure A modern Lisp language. Focus on concurrency. Lazyevaluation. Dynamic typing. Runs on the JVM.

Scala FP and OO. Strict evaluation by default, but supports lazyevaluation. Advanced static type system. Runs on the JVM.

OCaml FP and OO. Part of the ML family. Sometimes claimed tobe “faster than C”. Strict evaluation. Advanced static typesystem. Native-code compiler.

F# FP and OO. Based on OCaml. Strict evaluation by default,but supports lazy evaluation. Advanced static type system.Runs on the .NET CLR.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 7 / 58

Introduction

A Few Functional Programming Languages

Haskell Strong focus on functional purity. Lazy evaluation.Advanced static type system. Native-code compiler.

Erlang Focused around concurrency and distributed programming.Strict evaluation. Dynamic typing. Runs on the BEAM VM.

Clojure A modern Lisp language. Focus on concurrency. Lazyevaluation. Dynamic typing. Runs on the JVM.

Scala FP and OO. Strict evaluation by default, but supports lazyevaluation. Advanced static type system. Runs on the JVM.

OCaml FP and OO. Part of the ML family. Sometimes claimed tobe “faster than C”. Strict evaluation. Advanced static typesystem. Native-code compiler.

F# FP and OO. Based on OCaml. Strict evaluation by default,but supports lazy evaluation. Advanced static type system.Runs on the .NET CLR.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 7 / 58

Introduction

A Few Functional Programming Languages

Haskell Strong focus on functional purity. Lazy evaluation.Advanced static type system. Native-code compiler.

Erlang Focused around concurrency and distributed programming.Strict evaluation. Dynamic typing. Runs on the BEAM VM.

Clojure A modern Lisp language. Focus on concurrency. Lazyevaluation. Dynamic typing. Runs on the JVM.

Scala FP and OO. Strict evaluation by default, but supports lazyevaluation. Advanced static type system. Runs on the JVM.

OCaml FP and OO. Part of the ML family. Sometimes claimed tobe “faster than C”. Strict evaluation. Advanced static typesystem. Native-code compiler.

F# FP and OO. Based on OCaml. Strict evaluation by default,but supports lazy evaluation. Advanced static type system.Runs on the .NET CLR.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 7 / 58

Introduction

A Few Functional Programming Languages

Haskell Strong focus on functional purity. Lazy evaluation.Advanced static type system. Native-code compiler.

Erlang Focused around concurrency and distributed programming.Strict evaluation. Dynamic typing. Runs on the BEAM VM.

Clojure A modern Lisp language. Focus on concurrency. Lazyevaluation. Dynamic typing. Runs on the JVM.

Scala FP and OO. Strict evaluation by default, but supports lazyevaluation. Advanced static type system. Runs on the JVM.

OCaml FP and OO. Part of the ML family. Sometimes claimed tobe “faster than C”. Strict evaluation. Advanced static typesystem. Native-code compiler.

F# FP and OO. Based on OCaml. Strict evaluation by default,but supports lazy evaluation. Advanced static type system.Runs on the .NET CLR.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 7 / 58

Definition of Functional Programming

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 8 / 58

Definition of Functional Programming

So what exactly is Functional Programming?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 9 / 58

Definition of Functional Programming

Functional Programming, noun:

“ Functional Programming is a listof things you CAN’T do. ”

[7]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 10 / 58

Definition of Functional Programming

When programming in a functional style/language:

You can’t vary your variables.

You can’t mutate or change your state.

No while/for loops, sorry.

You can’t have side-effects.

You can’t control the order of execution (lazy evaluated languages).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 11 / 58

Definition of Functional Programming

When programming in a functional style/language:

You can’t vary your variables.

You can’t mutate or change your state.

No while/for loops, sorry.

You can’t have side-effects.

You can’t control the order of execution (lazy evaluated languages).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 11 / 58

Definition of Functional Programming

When programming in a functional style/language:

You can’t vary your variables.

You can’t mutate or change your state.

No while/for loops, sorry.

You can’t have side-effects.

You can’t control the order of execution (lazy evaluated languages).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 11 / 58

Definition of Functional Programming

When programming in a functional style/language:

You can’t vary your variables.

You can’t mutate or change your state.

No while/for loops, sorry.

You can’t have side-effects.

You can’t control the order of execution (lazy evaluated languages).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 11 / 58

Definition of Functional Programming

When programming in a functional style/language:

You can’t vary your variables.

You can’t mutate or change your state.

No while/for loops, sorry.

You can’t have side-effects.

You can’t control the order of execution (lazy evaluated languages).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 11 / 58

Definition of Functional Programming

Are you kidding me?

How can anyone program like this???

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 12 / 58

Definition of Functional Programming

GOTO 10

This sounds like

“You can’t have GOTO statements”

See Hughes and Dijkstra [1, 3]

Also framed in the negative (you can’t).

In hindsight we don’t really need GOTO’s.

In hindsight it is not about what you cannot do.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 13 / 58

Definition of Functional Programming

GOTO 10

This sounds like

“You can’t have GOTO statements”

See Hughes and Dijkstra [1, 3]

Also framed in the negative (you can’t).

In hindsight we don’t really need GOTO’s.

In hindsight it is not about what you cannot do.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 13 / 58

Definition of Functional Programming

GOTO 10

This sounds like

“You can’t have GOTO statements”

See Hughes and Dijkstra [1, 3]

Also framed in the negative (you can’t).

In hindsight we don’t really need GOTO’s.

In hindsight it is not about what you cannot do.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 13 / 58

Definition of Functional Programming

Structured Programming and Functional Programming

Structured Programming introduced subroutines with fixed entry/exitpoints (instead of GOTO’s), resulting in improvedmodularity.

Functional Programming provides similar important benefits – more aboutthis later.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 14 / 58

Definition of Functional Programming

Structured Programming and Functional Programming

Structured Programming introduced subroutines with fixed entry/exitpoints (instead of GOTO’s), resulting in improvedmodularity.

Functional Programming provides similar important benefits – more aboutthis later.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 14 / 58

Definition of Functional Programming

We need a better definition for Functional Programming.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 15 / 58

Definition of Functional Programming

Functional Programming, noun:

“ Functional programming is so called because a programconsists entirely of functions. ”

— John Hughes, Why Functional Programming Matters [1, p. 1]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 16 / 58

Definition of Functional Programming

OK... so what exactly is a function?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 17 / 58

Function Recap

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 18 / 58

Function Recap

An example function

f (x) = 2x + 3

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 19 / 58

Function Recap

Variables in functions

f (x) = 2x + 3When we evaluate the function:

f (4) = 2 ∗ 4 + 3 = 11

The value of x will not change inside the function body.

No x = 4 and later x = 21 in the same function body.

Same input, same output. Every time.

In other words, we can replace any occurrence of f (4) with 11(Referential Transparency)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 20 / 58

Function Recap

Variables in functions

f (x) = 2x + 3When we evaluate the function:

f (4) = 2 ∗ 4 + 3 = 11

The value of x will not change inside the function body.

No x = 4 and later x = 21 in the same function body.

Same input, same output. Every time.

In other words, we can replace any occurrence of f (4) with 11(Referential Transparency)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 20 / 58

Function Recap

Variables in functions

f (x) = 2x + 3When we evaluate the function:

f (4) = 2 ∗ 4 + 3 = 11

The value of x will not change inside the function body.

No x = 4 and later x = 21 in the same function body.

Same input, same output. Every time.

In other words, we can replace any occurrence of f (4) with 11(Referential Transparency)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 20 / 58

Function Recap

Variables in functions

f (x) = 2x + 3When we evaluate the function:

f (4) = 2 ∗ 4 + 3 = 11

The value of x will not change inside the function body.

No x = 4 and later x = 21 in the same function body.

Same input, same output. Every time.

In other words, we can replace any occurrence of f (4) with 11(Referential Transparency)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 20 / 58

Function Recap

Variables in functions

f (x) = 2x + 3When we evaluate the function:

f (4) = 2 ∗ 4 + 3 = 11

The value of x will not change inside the function body.

No x = 4 and later x = 21 in the same function body.

Same input, same output. Every time.

In other words, we can replace any occurrence of f (4) with 11(Referential Transparency)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 20 / 58

Function Recap

Functions can call other functions

g(x) = f (x) + 1

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 21 / 58

Function Recap

Values are functions

Constant values are just functions with no input parameters

k = 42def k():

return 42

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 22 / 58

Function Recap

Functions can be combined

h(x) = f (g(x))

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 23 / 58

Function Recap

Higher-order Functions

Functions can take functions as input and/or returnfunctions as the result.

h(p, q, x) = p(x) + q(2)

h(f , g , 3) = f (3) + g(2)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 24 / 58

Function Recap

Higher-order Functions

Functions can take functions as input and/or returnfunctions as the result.

h(p, q, x) = p(x) + q(2)h(f , g , 3) = f (3) + g(2)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 24 / 58

Function Recap

Higher-order Functions

The derivative of cos(x) returns another function.

ddx cos(x) = − sin(x)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 25 / 58

Function Recap

A functional program consists entirely of functions

def main(args):

result = do_something_with_args(args)

print result

def do_something_with_args(args):

return ’-’.join(args[1:])

./justfunctions.py hello functional programming

hello-functional-programming

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 26 / 58

Function Recap

A functional program consists entirely of functions

main :: IO()

main = do

args <- getArgs

let result = do_something_with_args args

putStrLn result

do_something_with_args :: [String] -> String

do_something_with_args args = intercalate "-" args

./justfunctions hello functional programming

hello-functional-programming

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 27 / 58

Common FP Idioms

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 28 / 58

Common FP Idioms Recursion

Recursive function: Haskell

doubleAll :: Num a => [a] -> [a]

doubleAll [] = []

doubleAll (x:xs) = x*2 : doubleAll xs

Example use in the interactive interpreter:

Prelude Main> doubleAll [8,2,3]

[16,4,6]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 29 / 58

Common FP Idioms Recursion

Recursive function: Python

def doubleAll(numbers):

if numbers == []:

return []

else:

first = numbers[0]

rest = numbers[1:]

return [first * 2] + doubleAll(rest)

Example use in the interactive interpreter:

>>> doubleAll([8,2,3])

[16, 4, 6]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 30 / 58

Common FP Idioms Recursion

An iterative version in Python

def doubleAll(numbers):

doubled = []

for num in numbers:

doubled.append(num * 2)

return doubled

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 31 / 58

Common FP Idioms Pattern Matching

Pattern Matching: Haskell

doubleAll :: Num a => [a] -> [a]

doubleAll [] = []

doubleAll (x:xs) = x*2 : doubleAll xs

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 32 / 58

Common FP Idioms Higher-order Functions

Higher-order functions: Python

f (x) = 2x + 3g(x) = f (x) + 1h(p, q, x) = p(x) + q(2)

def f(x):

return (2*x) + 3

def g(x):

return f(x) + 1

def h(func_a, func_b, x):

return func_a(x) + func_b(2)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 33 / 58

Common FP Idioms Higher-order Functions

Higher-order functions: Haskell

f (x) = 2x + 3g(x) = f (x) + 1h(p, q, x) = p(x) + q(2)

f x = (2*x) + 3

g x = (f x) + 1

h :: (Int->Int) -> (Int->Int) -> Int -> Int

h func_a func_b x = (func_a x) + (func_b 2)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 34 / 58

Higher-order Functions and Lists

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 35 / 58

Higher-order Functions and Lists

3 Basic List Operations

Map Convert each element of a list into some other value.Example: Convert a list of students to a list of exam scores.

Filter Get a subset of a list based on some condition. Example:Filter the entire list of students down to only those thatpassed the exam.

Fold Reduce a list of items to a single value. Example: Reducethe list of students to a single string of all names.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 36 / 58

Higher-order Functions and Lists

3 Basic List Operations

Map Convert each element of a list into some other value.Example: Convert a list of students to a list of exam scores.

Filter Get a subset of a list based on some condition. Example:Filter the entire list of students down to only those thatpassed the exam.

Fold Reduce a list of items to a single value. Example: Reducethe list of students to a single string of all names.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 36 / 58

Higher-order Functions and Lists

3 Basic List Operations

Map Convert each element of a list into some other value.Example: Convert a list of students to a list of exam scores.

Filter Get a subset of a list based on some condition. Example:Filter the entire list of students down to only those thatpassed the exam.

Fold Reduce a list of items to a single value. Example: Reducethe list of students to a single string of all names.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 36 / 58

Higher-order Functions and Lists

Map

doubleAll :: Num a => [a] -> [a]

doubleAll [] = []

doubleAll (x:xs) = x*2 : doubleAll xs

Looks very similar to the builtin map function:

map :: (a -> b) -> [a] -> [b]

map _ [] = []

map f (x:xs) = f x : map f xs

So our doubleAll can actually be simplified as:

doubleAll = map (*2)

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 37 / 58

Higher-order Functions and Lists

Student Data

data Student = Student { firstName :: String

, lastName :: String

, finalExamScore :: Double}

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 38 / 58

Higher-order Functions and Lists

Student Data

[Student {firstName="John",

lastName="Deer",

finalExamScore=60},

Student {firstName="Billy",

lastName="Bob",

finalExamScore=49.1},

Student {firstName="Jane",

lastName="Doe",

finalExamScore=89},

Student {firstName="Jack",

lastName="Johnson",

finalExamScore=29.3}]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 39 / 58

Higher-order Functions and Lists

Map

Map type signature:

map :: (a -> b) -> [a] -> [b]

Map on student data:

allscores :: [Student] -> [Double]

allscores students = map finalExamScore students

finalExamScore type signature:

finalExamScore :: Student -> Double

Output:

Final Exam Scores: [60.0,49.1,89.0,29.3]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 40 / 58

Higher-order Functions and Lists

Filter

Filter type signature:

filter :: (a -> Bool) -> [a] -> [a]

Filter on student data:

passed :: [Student] -> [Student]

passed students = filter has_passed students

has_passed :: Student -> Bool

has_passed student = finalExamScore student >= 60

Output:

Students that have passed:

[John Deer (60.0),Jane Doe (89.0)]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 41 / 58

Higher-order Functions and Lists

Fold

Fold type signature:

foldl :: (a -> b -> a) -> a -> [b] -> a

Fold on student data:

namecat :: [Student] -> String

namecat students = foldl catfun "" students

catfun :: String -> Student -> String

catfun acc student = acc ++ (firstName student) ++ "\n"

Output:

"John\nBilly\nJane\nJack\n"

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 42 / 58

Higher-order Functions and Lists

Shortened Map, Filter, Fold

allscores = map finalExamScore

passed = filter has_passed

has_passed student = finalExamScore student >= 60

namecat = foldl catfun ""

where catfun = (\acc student ->

acc ++ (firstName student) ++ "\n")

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 43 / 58

Higher-order Functions and Lists

Imperative Filter Example

class Student:

def __init__(self, firstname, lastname, finalexamscore):

self.firstname = firstname

self.lastname = lastname

self.finalexamscore = finalexamscore

def has_passed(self):

return self.finalexamscore >= 60

def passed(students):

passed_students = []

for student in students:

if student.has_passed():

passed_students.append(student)

return passed_students

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 44 / 58

Advantages of Functional Programming

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 45 / 58

Advantages of Functional Programming

Perlisism #19

“ A language that doesn’t affect the way you think aboutprogramming, is not worth knowing. ”

— Alan Perlis[5]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 46 / 58

Advantages of Functional Programming

Advantages of Functional Programming

Changes the way you think about programming and problem solving.

Improvements on the types of abstractions we can do with eg.higher-order functions.

Lock-free concurrency.

Improved ways of testing - QuickCheck.

More effective reasoning about code.

Declare possible Null values explicitly if you need them. GoodbyeNullPointerException (mostly).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 47 / 58

Advantages of Functional Programming

Advantages of Functional Programming

Changes the way you think about programming and problem solving.

Improvements on the types of abstractions we can do with eg.higher-order functions.

Lock-free concurrency.

Improved ways of testing - QuickCheck.

More effective reasoning about code.

Declare possible Null values explicitly if you need them. GoodbyeNullPointerException (mostly).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 47 / 58

Advantages of Functional Programming

Advantages of Functional Programming

Changes the way you think about programming and problem solving.

Improvements on the types of abstractions we can do with eg.higher-order functions.

Lock-free concurrency.

Improved ways of testing - QuickCheck.

More effective reasoning about code.

Declare possible Null values explicitly if you need them. GoodbyeNullPointerException (mostly).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 47 / 58

Advantages of Functional Programming

Advantages of Functional Programming

Changes the way you think about programming and problem solving.

Improvements on the types of abstractions we can do with eg.higher-order functions.

Lock-free concurrency.

Improved ways of testing - QuickCheck.

More effective reasoning about code.

Declare possible Null values explicitly if you need them. GoodbyeNullPointerException (mostly).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 47 / 58

Advantages of Functional Programming

Advantages of Functional Programming

Changes the way you think about programming and problem solving.

Improvements on the types of abstractions we can do with eg.higher-order functions.

Lock-free concurrency.

Improved ways of testing - QuickCheck.

More effective reasoning about code.

Declare possible Null values explicitly if you need them. GoodbyeNullPointerException (mostly).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 47 / 58

Advantages of Functional Programming

Advantages of Functional Programming

Changes the way you think about programming and problem solving.

Improvements on the types of abstractions we can do with eg.higher-order functions.

Lock-free concurrency.

Improved ways of testing - QuickCheck.

More effective reasoning about code.

Declare possible Null values explicitly if you need them. GoodbyeNullPointerException (mostly).

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 47 / 58

Disdvantages of Functional Programming

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 48 / 58

Disdvantages of Functional Programming

Disadvantages of Functional Programming

Steep learning curve.

There are some very cryptic concepts.

Tools/IDE’s are not as advanced as the mainstream equivalents.

Order of execution may be difficult to reason about in a lazy language.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 49 / 58

Disdvantages of Functional Programming

Disadvantages of Functional Programming

Steep learning curve.

There are some very cryptic concepts.

Tools/IDE’s are not as advanced as the mainstream equivalents.

Order of execution may be difficult to reason about in a lazy language.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 49 / 58

Disdvantages of Functional Programming

Disadvantages of Functional Programming

Steep learning curve.

There are some very cryptic concepts.

Tools/IDE’s are not as advanced as the mainstream equivalents.

Order of execution may be difficult to reason about in a lazy language.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 49 / 58

Disdvantages of Functional Programming

Disadvantages of Functional Programming

Steep learning curve.

There are some very cryptic concepts.

Tools/IDE’s are not as advanced as the mainstream equivalents.

Order of execution may be difficult to reason about in a lazy language.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 49 / 58

Disdvantages of Functional Programming

Unfamiliar Territory

Functional Programming is unfamiliar territory for most.

“ If you want everything to be familiar you will never learnanything new. ”

— Rich Hickey, author of Clojure[6]

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 50 / 58

Companies using Functional Programming

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 51 / 58

Companies using Functional Programming

Companies In South Africa

Pattern Matched Technologies, Midrand Using Erlang for all systems, eg.processing high volumes of financial transactions.

Eldo Energy, Johannesburg Using Clojure for automated meter readingand intelligent monitoring of consumer energy.

Rheo Systems, Pretoria Using Clojure for supply chain integration.

Yuppiechef, Cape Town Using Clojure for their Warehouse ManagementSystem.

Effective Control Systems, Kyalami Using Erlang for printer management.

Mira Networks, Somerset West Using Erlang for billing administration andmobile development.

Amazon.com, Cape Town Using Scala in EC2.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 52 / 58

Companies using Functional Programming

Companies In South Africa

Pattern Matched Technologies, Midrand Using Erlang for all systems, eg.processing high volumes of financial transactions.

Eldo Energy, Johannesburg Using Clojure for automated meter readingand intelligent monitoring of consumer energy.

Rheo Systems, Pretoria Using Clojure for supply chain integration.

Yuppiechef, Cape Town Using Clojure for their Warehouse ManagementSystem.

Effective Control Systems, Kyalami Using Erlang for printer management.

Mira Networks, Somerset West Using Erlang for billing administration andmobile development.

Amazon.com, Cape Town Using Scala in EC2.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 52 / 58

Companies using Functional Programming

Companies In South Africa

Pattern Matched Technologies, Midrand Using Erlang for all systems, eg.processing high volumes of financial transactions.

Eldo Energy, Johannesburg Using Clojure for automated meter readingand intelligent monitoring of consumer energy.

Rheo Systems, Pretoria Using Clojure for supply chain integration.

Yuppiechef, Cape Town Using Clojure for their Warehouse ManagementSystem.

Effective Control Systems, Kyalami Using Erlang for printer management.

Mira Networks, Somerset West Using Erlang for billing administration andmobile development.

Amazon.com, Cape Town Using Scala in EC2.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 52 / 58

Companies using Functional Programming

Companies In South Africa

Pattern Matched Technologies, Midrand Using Erlang for all systems, eg.processing high volumes of financial transactions.

Eldo Energy, Johannesburg Using Clojure for automated meter readingand intelligent monitoring of consumer energy.

Rheo Systems, Pretoria Using Clojure for supply chain integration.

Yuppiechef, Cape Town Using Clojure for their Warehouse ManagementSystem.

Effective Control Systems, Kyalami Using Erlang for printer management.

Mira Networks, Somerset West Using Erlang for billing administration andmobile development.

Amazon.com, Cape Town Using Scala in EC2.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 52 / 58

Companies using Functional Programming

Companies In South Africa

Pattern Matched Technologies, Midrand Using Erlang for all systems, eg.processing high volumes of financial transactions.

Eldo Energy, Johannesburg Using Clojure for automated meter readingand intelligent monitoring of consumer energy.

Rheo Systems, Pretoria Using Clojure for supply chain integration.

Yuppiechef, Cape Town Using Clojure for their Warehouse ManagementSystem.

Effective Control Systems, Kyalami Using Erlang for printer management.

Mira Networks, Somerset West Using Erlang for billing administration andmobile development.

Amazon.com, Cape Town Using Scala in EC2.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 52 / 58

Companies using Functional Programming

Companies In South Africa

Pattern Matched Technologies, Midrand Using Erlang for all systems, eg.processing high volumes of financial transactions.

Eldo Energy, Johannesburg Using Clojure for automated meter readingand intelligent monitoring of consumer energy.

Rheo Systems, Pretoria Using Clojure for supply chain integration.

Yuppiechef, Cape Town Using Clojure for their Warehouse ManagementSystem.

Effective Control Systems, Kyalami Using Erlang for printer management.

Mira Networks, Somerset West Using Erlang for billing administration andmobile development.

Amazon.com, Cape Town Using Scala in EC2.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 52 / 58

Companies using Functional Programming

Companies In South Africa

Pattern Matched Technologies, Midrand Using Erlang for all systems, eg.processing high volumes of financial transactions.

Eldo Energy, Johannesburg Using Clojure for automated meter readingand intelligent monitoring of consumer energy.

Rheo Systems, Pretoria Using Clojure for supply chain integration.

Yuppiechef, Cape Town Using Clojure for their Warehouse ManagementSystem.

Effective Control Systems, Kyalami Using Erlang for printer management.

Mira Networks, Somerset West Using Erlang for billing administration andmobile development.

Amazon.com, Cape Town Using Scala in EC2.

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 52 / 58

Where do we go from here?

Table of Contents

1 Introduction

2 Definition of Functional Programming

3 Function Recap

4 Common FP IdiomsRecursionPattern MatchingHigher-order Functions

5 Higher-order Functions and Lists

6 Advantages of Functional Programming

7 Disdvantages of Functional Programming

8 Companies using Functional Programming

9 Where do we go from here?

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 53 / 58

Where do we go from here?

Lambda Luminaries – @lambdaluminaryLocal functional programming user group

We meet once a month, on the second Monday of the month.http://www.meetup.com/lambda-luminaries/

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 54 / 58

Where do we go from here?

Online Courses

Functional Programming Principles in ScalaEPFL Universityhttps://www.coursera.org/course/progfun

School of HaskellFP Completehttps://www.fpcomplete.com/school

Programming LanguagesUniversity of Washingtonhttps://www.coursera.org/course/proglang

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 55 / 58

Where do we go from here?

Books

Miran LipovacaLearn You a Haskell for Great Good!http://learnyouahaskell.com/

Fred HebertLearn You Some Erlang for Great Good!http://learnyousomeerlang.com/

Yaron Minski, Anil Madhavapeddy, Jason HickeyReal World OCamlhttps://realworldocaml.org/

Paul Chiusano, Runar BjarnasonFunctional Programming in Scalahttp://www.manning.com/bjarnason/

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 56 / 58

Where do we go from here?

References I

John HughesWhy Functional Programming Mattershttp:

//www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf

John CarmackFunctional Programming in C++http://www.altdevblogaday.com/2012/04/26/

functional-programming-in-c/

Edsger W. DijkstraGo To Statement Considered Harmfulhttp://www.u.arizona.edu/~rubinson/copyright_violations/

Go_To_Considered_Harmful.html

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 57 / 58

Where do we go from here?

References II

Tweet by Michael Feathershttps://twitter.com/mfeathers/status/29581296216

Alan Jay Perlishttp://www.cs.yale.edu/quotes.html

Rich Hickeyhttp://www.infoq.com/presentations/Simple-Made-Easy

Andreas PauleyAn Introduction to Functional Programminghttps://github.com/apauley/fp_presentation

Andreas Pauley – @apauley (Pattern Matched TechnologiesLambda Luminaries @lambdaluminary)Functional Programming September 2, 2013 58 / 58

Recommended