SlideShare a Scribd company logo
1 of 85
Download to read offline
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
An Introduction to Functional Programming
Andreas Pauley – @apauley
Jozi JUG
July 28, 2014
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
@lambdaluminary
We meet once a month, on the second Monday of the month.
http://www.meetup.com/lambda-luminaries/
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Jemstep
Retirement portfolio analysis in Scala.
http://www.jemstep.com/
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Who likes FP?
“ And that’s why I think functional
programming is a natural successor to
object-oriented programming. ”
— Dave Thomas, Pragmatic Programmers [2]
“ Without understanding functional
programming, you can’t invent MapReduce ”
— Joel Spolsky [3]
“ ...it’s almost certainly true that functional
programming is the next big thing. ”
— Uncle Bob Martin [4]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
“ No matter what language you work
in, programming in a functional style
provides benefits. You should do it
whenever it is convenient, and you
should think hard about the decision
when it isn’t convenient. ”
— John Carmack, ID Software [5]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
But what exactly is
“Functional Programming”?
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A simple programming example
Say I give you an array of integers, and I want every
one of them doubled.
How would you write it?
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A simple programming example
I have this:
[1,3,6]
I want this:
[2,6,12]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A simple programming example
public static void doubleAll(int[] numbers) {
for (int i=0; i < numbers.length; i++) {
numbers[i] = numbers[i] * 2;
}
}
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A simple programming example
Sorry, I forgot to mention that you cannot do
in-place mutation on the list of numbers I give you.
Please try again.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A simple programming example
Our first try had a void return type:
public static void doubleAll(int[] numbers) {
for (int i=0; i < numbers.length; i++) {
numbers[i] = numbers[i] * 2;
}
}
Now we have to return a result:
public static int[] doubleAll(int[] numbers) {
int[] nums2 = new int[numbers.length];
for (int i=0; i < numbers.length; i++) {
nums2[i] = numbers[i] * 2;
}
return nums2;
}
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A simple programming example
Looking much better, but you can’t mutate any
collection, appending to the new array won’t work.
Also, you can’t vary your variables (i++).
Please try again.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A simple programming example
???
public static int[] doubleAll(int[] numbers) {
int[] nums2 = new int[numbers.length];
for (int i=0; i < numbers.length; i++) {
nums2[i] = numbers[i] * 2;
}
return nums2;
}
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Let’s try giving a definition of
Functional Programming
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Functional Programming, noun:
Functional Programming is a
list of things you CAN’T do.
[10]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
You can’t vary your variables
1> X = 42.
42
2> X = X + 1.
** exception error:
no match of right hand
side value 43
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
No while/for loops. Sorry :-(
int i;
for (i=1; i<=3; i++) {
System.out.println(i);
}
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
You can’t mutate/change your data structures
Python
>>> list1 = [1,2,3]
>>> list2 = list1
>>> print list1.reverse()
None
>>> list1
[3, 2, 1]
>>> list2
[3, 2, 1]
Haskell
> let list1 = [1,2,3]
> let list2 = list1
> reverse(list1)
[3,2,1]
> list1
[1,2,3]
> list2
[1,2,3]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
You can’t have any side e↵ects
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Are you kidding me?
How can anyone program like this???
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
GOTO 10
This sounds like
“You can’t have GOTO statements”
See Hughes and Dijkstra [1, 6]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
It’s not about what we cannot
do.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
We need a better definition of
Functional Programming.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Programming Paradigms
(Very Simplified)
Imperative Declarative
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Functional Programming, noun:
“ Functional programming is so called because a
program consists entirely of functions. ”
— John Hughes, Why Functional Programming Matters [1, p. 1]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
OK... so what exactly is a function?
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
An example function
f(x) = 2x2 2x + 3
1 1 2 3
4
6
8
10
12
14
x
y
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Variables in functions
f(x) = 2x2 2x + 3
When we evaluate the function:
f(2) = 8 4 + 3 = 7
• The value of x will not change inside the function body.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Variables in functions
f(x) = 2x2 2x + 3
When we evaluate the function:
f(2) = 8 4 + 3 = 7
• The value of x will not change inside the function body.
• Same input, same output. Every time. (Referential
Transparency)
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Variables in functions
f(x) = 2x2 2x + 3
When we evaluate the function:
f(2) = 8 4 + 3 = 7
• The value of x will not change inside the function body.
• Same input, same output. Every time. (Referential
Transparency)
• We can call f multiple times without any side e↵ects.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Variables in functions
f(x) = 2x2 2x + 3
When we evaluate the function:
f(2) = 8 4 + 3 = 7
• The value of x will not change inside the function body.
• Same input, same output. Every time. (Referential
Transparency)
• We can call f multiple times without any side e↵ects.
• We don’t have to recalculate f(2), we can replace any
occurrence of f(2) with 7.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Varying variables does not make sense
x = x + 1
x x = 1
0 = 1
) x 6= x + 1
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Values are functions
Constant values are just functions with no input parameters
x = 42
Python function definition:
def x():
return 42
Haskell function definition:
x = 42
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Functions can be composed
h(x) = (f g)(x) = f(g(x))
or
h = f g
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Higher-order Functions
Functions can take functions as input.
Functions can return functions as the result.
h(f, g, x) = f(x) + g(2)
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Higher-order Functions
The derivative of f(x) returns another function.
f(x) = 2x2
2x + 3
d
dxf(x) = 4x 2
1 1 2 3
5
10
15
x
y
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A functional program consists entirely of functions
def main():
time = datetime.now()
args = sys.argv[1:]
print outputString(time, args)
def outputString(time, args):
return str(time) + " " + joinArgs(args)
def joinArgs(args):
return "-".join(args)
$ ./justfunctions.py Hello from Python
2014-02-15 10:36:42.062697 Hello-from-Python
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
A functional program consists entirely of functions
main :: IO()
main = do
time <- getCurrentTime
args <- getArgs
putStrLn (outputString time args)
outputString :: UTCTime -> [String] -> String
outputString time args =
show(time) ++ " " ++ joinArgs(args)
joinArgs :: [String] -> String
joinArgs = intercalate "-"
$ ./justfunctions Hello from Haskell
2014-02-15 08:36:50.822728 UTC Hello-from-Haskell
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Some Haskell Syntax
Python:
def outputString(time, args):
return str(time) + " " + joinArgs(args)
Haskell:
outputString :: UTCTime -> [String] -> String
outputString time args =
show(time) ++ " " ++ joinArgs(args)
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Recursive function: Haskell
doubleAll :: [Int] -> [Int]
doubleAll [] = []
doubleAll (x:xs) = x*2 : doubleAll xs
Example use in the interactive interpreter:
Prelude Main> doubleAll [8,2,3]
[16,4,6]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Recursive function expanded
doubleAll [] = []
doubleAll (x:xs) = x*2 : doubleAll xs
doubleAll [8,2,3]
16 : (doubleAll [2,3])
16 : 4 : (doubleAll [3])
16 : 4 : 6 : (doubleAll [])
16 : 4 : 6 : []
16 : 4 : [6]
16 : [4,6]
[16,4,6]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
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]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Pattern Matching: Haskell
doubleAll :: [Int] -> [Int]
doubleAll [] = []
doubleAll (x:xs) = x*2 : doubleAll xs
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Higher-order Functions
3 Basic List Operations
Map Convert each element of a list into some other value.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Higher-order Functions
3 Basic List Operations
Map Convert each element of a list into some other value.
Filter Get a subset of a list based on some condition.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Higher-order Functions
3 Basic List Operations
Map Convert each element of a list into some other value.
Filter Get a subset of a list based on some condition.
Fold Reduce a list of items to a single value.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Map
Apply a function to each element of a list, and you get a new list.
a1 a2 a3 ... an
b1 b2 b3
... bn
f(a1) f(an)
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Map
doubleAll :: Num a => [a] -> [a]
doubleAll = map (*2)
8 2 3
16 4 6
⇤2 ⇤2 ⇤2
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Account Data
data Bank = ABSA | Capitec | FNB | Nedbank | SBSA
data Account = Account {bank :: Bank,
accNum :: String,
owner :: String,
balance :: Amount}
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Account Data
[Account {accNum="4076814233",
owner="J. Doe",
balance=(Amount 123000.23),
bank=ABSA},
Account {accNum="6868773585",
owner="J. Black",
balance=(Amount 5782347.99),
bank=FNB},
Account {accNum="4055892156",
owner="A. Kay",
balance=(Amount 100),
bank=ABSA},
Account {accNum="6584539813",
owner="S. Jones",
balance=(Amount 2937361.45),
bank=FNB}]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Map
Map on account data:
balances :: [Account] -> [Amount]
balances accounts = map balance accounts
acc1 acc2 acc3 acc4 acc5
bal1 bal2 bal3 bal4 bal5
balance(acc1) balance(acc5)
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Filter
acc1 acc2 acc3 acc4 acc5
acc1 acc3 acc5
in? in? in? in? in?
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Filter
Filter on account data:
topAccounts :: [Account] -> [Account]
topAccounts accounts = filter isRich accounts
isRich :: Account -> Bool
isRich acc = balance acc >= (Amount 1000000)
Output:
*Main> topAccounts accounts
[FNB 6868773585 (J. Black) R5782347.99,
FNB 6584539813 (S. Jones) R2937361.45]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Fold/Reduce/Inject
foldl (+) 0 [8,2,3]
13
0 8 2 3
8 2 3
10 3
13
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Fold/Reduce/Inject
balanceSum :: [Account] -> Amount
balanceSum accounts = foldl (+) 0 (balances accounts)
0 bal1 bal2 bal3
sum bal2 bal3
sum bal3
sum
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Function Composition
balanceSum :: [Account] -> Amount
balanceSum accounts = foldl (+) 0 (balances accounts)
0 bal1 bal2 bal3
sum bal2 bal3
sum bal3
sum
s2 :: [Account] -> Amount
s2 = balances |> (foldl(+)0)
h(x) = (f g)(x) = f(g(x))
h = f g
s3 = f1 balances
s3 :: [Account] -> Amount
s3 = (foldl(+)0) . balances
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
balancesPerBank
foldl insertBalance Map.empty accounts
{} acc1 acc2 acc3
map acc2 acc3
map acc3
map
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Fold
type BankMap = Map Bank Amount
balancesPerBank :: [Account] -> BankMap
balancesPerBank = foldl insertBalance Map.empty
Output:
*Main> balancesPerBank accounts
fromList [(ABSA,R123100.23),(FNB,R8719709.44)]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Fold
type BankMap = Map Bank Amount
balancesPerBank :: [Account] -> BankMap
balancesPerBank = foldl insertBalance Map.empty
insertBalance :: BankMap -> Account -> BankMap
insertBalance bankmap account =
Map.insert key value bankmap
where key = bank account
value = addBalance bankmap account
addBalance :: BankMap -> Account -> Amount
addBalance bankmap account =
case (Map.lookup (bank account) bankmap) of
Nothing -> balance account
Just bal -> (balance account) + bal
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Programming Paradigms
(Very Simplified)
Imperative Declarative
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
In imperative programming:
• Your variables can vary any time!
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
In imperative programming:
• Your variables can vary any time!
• You have to use locks to be thread-safe!
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
In imperative programming:
• Your variables can vary any time!
• You have to use locks to be thread-safe!
• You have to write your own loops for the most basic list
operations!
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
In imperative programming:
• Your variables can vary any time!
• You have to use locks to be thread-safe!
• You have to write your own loops for the most basic list
operations!
• Your data structures are mutable!
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
In imperative programming:
• Your variables can vary any time!
• You have to use locks to be thread-safe!
• You have to write your own loops for the most basic list
operations!
• Your data structures are mutable!
• You have to defensively make copies of data to prevent bugs!
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
In imperative programming:
• Your variables can vary any time!
• You have to use locks to be thread-safe!
• You have to write your own loops for the most basic list
operations!
• Your data structures are mutable!
• You have to defensively make copies of data to prevent bugs!
• You have to defensively check for null values!
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
In imperative programming:
• Your variables can vary any time!
• You have to use locks to be thread-safe!
• You have to write your own loops for the most basic list
operations!
• Your data structures are mutable!
• You have to defensively make copies of data to prevent bugs!
• You have to defensively check for null values!
• You have to think about implicit state! (this, self)
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
In imperative programming:
• Your variables can vary any time!
• You have to use locks to be thread-safe!
• You have to write your own loops for the most basic list
operations!
• Your data structures are mutable!
• You have to defensively make copies of data to prevent bugs!
• You have to defensively check for null values!
• You have to think about implicit state! (this, self)
• Code is generally riddled with side e↵ects!
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Are you kidding me?
How can anyone program like this???
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Unit tests
Start writing the unit tests for
your existing code in a
functional programming
language
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Join the anti-for campaign
Less loops, more
map/filter/fold
http://weblogs.asp.net/podwysocki/archive/2009/06/26/
the-anti-for-campaign.aspx
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Treat side e↵ects as a first-class concern
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Learn a functional language
“ A language that doesn’t a↵ect the way you think
about programming, is not worth knowing. ”
— Alan Perlis[8]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Disclaim your inheritance
Write non-trivial code without
using objects and inheritance.
Get re-usability with higher-order functions.
Try to minimise moving parts instead of
encapsulating moving parts. [7]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Join our group
@lambdaluminary
We meet once a month, on the second Monday of the month.
http://www.meetup.com/lambda-luminaries/
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Get out of your comfort zone
Functional Programming is unfamiliar territory for
most.
“ If you want everything to be familiar you will
never learn anything new. ”
— Rich Hickey, author of Clojure[9]
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Companies In South Africa
Jemstep, Sandton Using Scala for Fund Analysis
Allan Gray, Cape Town Using Scala for backend logic and system
integration.
Yuppiechef, Cape Town Using Clojure for their Warehouse
Management System.
Cognician, Cape Town Using Clojure to create coaching/learning
modules.
Eldo Energy, Johannesburg Using Clojure for automated meter
reading and intelligent monitoring of consumer
energy.
Rheo Systems, Pretoria Using Clojure for supply chain integration.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Companies In South Africa
Pattern Matched Technologies, Midrand Using Erlang for all
systems, eg. processing high volumes of financial
transactions.
E↵ective Control Systems, Kyalami Using Erlang for printer
management.
Mira Networks, Somerset West Using Erlang for billing
administration and mobile development.
Kotive Using Scala for designing workflow processes.
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Online Courses
Functional Thinking by Neal Ford
O’ Reilly
http://shop.oreilly.com/product/0636920030393.do
Functional Programming Principles in Scala
EPFL University
https://www.coursera.org/course/progfun
School of Haskell
FP Complete
https://www.fpcomplete.com/school
Programming Languages
University of Washington
https://www.coursera.org/course/proglang
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
Books
Miran Lipovaˇca
Learn You a Haskell for Great Good!
http://learnyouahaskell.com/
Fred H´ebert
Learn You Some Erlang for Great Good!
http://learnyousomeerlang.com/
Yaron Minski, Anil Madhavapeddy, Jason Hickey
Real World OCaml
https://realworldocaml.org/
Paul Chiusano, R´unar Bjarnason
Functional Programming in Scala
http://www.manning.com/bjarnason/
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
References I
John Hughes
Why Functional Programming Matters
http://www.cs.kent.ac.uk/people/staff/dat/miranda/
whyfp90.pdf
Dave Thomas
Programming Elixir, A Gentle Introduction
http://theprosegarden.com/part-1-of/
Joel Spolsky
Can Your Programming Language Do This?
http:
//www.joelonsoftware.com/items/2006/08/01.html
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
References II
Robert Martin
Functional Programming Basics
http://pragprog.com/magazines/2013-01/
functional-programming-basics
John Carmack
Functional Programming in C++
http://www.altdevblogaday.com/2012/04/26/
functional-programming-in-c/
Edsger W. Dijkstra
Go To Statement Considered Harmful
http://www.u.arizona.edu/~rubinson/copyright_
violations/Go_To_Considered_Harmful.html
Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
References III
Tweet by Michael Feathers
https://twitter.com/mfeathers/status/29581296216
Alan Jay Perlis
http://www.cs.yale.edu/quotes.html
Rich Hickey
http:
//www.infoq.com/presentations/Simple-Made-Easy
Andreas Pauley
An Introduction to Functional Programming
https://github.com/apauley/fp_presentation

More Related Content

What's hot

The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)Scott Wlaschin
 
Mixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMark Needham
 
Functions in c++
Functions in c++Functions in c++
Functions in c++Maaz Hasan
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Scott Wlaschin
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in rubyKoen Handekyn
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014Phillip Trelford
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in PythonColin Su
 
Function class in c++
Function class in c++Function class in c++
Function class in c++Kumar
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingEelco Visser
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionEelco Visser
 

What's hot (20)

Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)The Power of Composition (NDC Oslo 2020)
The Power of Composition (NDC Oslo 2020)
 
Mixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented languageMixing functional programming approaches in an object oriented language
Mixing functional programming approaches in an object oriented language
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 

Similar to An Introduction to Functional Programming at the Jozi Java User Group

Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Functional Programming in R
Functional Programming in RFunctional Programming in R
Functional Programming in RSoumendra Dhanee
 
Programming in c function
Programming in c functionProgramming in c function
Programming in c functionParvez Ahmed
 
Spreadsheets: Functional Programming for the Masses
Spreadsheets: Functional Programming for the MassesSpreadsheets: Functional Programming for the Masses
Spreadsheets: Functional Programming for the Masseskfrdbs
 
Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoJoel Falcou
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programmingDhaval Dalal
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaDamian Jureczko
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patternsOlivier Bacs
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)Tech in Asia ID
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad Fabernovel
 
Functional Programming in R
Functional Programming in RFunctional Programming in R
Functional Programming in RDavid Springate
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015senejug
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++ppd1961
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 

Similar to An Introduction to Functional Programming at the Jozi Java User Group (20)

Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Functional Programming in R
Functional Programming in RFunctional Programming in R
Functional Programming in R
 
Programming in c function
Programming in c functionProgramming in c function
Programming in c function
 
Refactoring
RefactoringRefactoring
Refactoring
 
Refactoring
RefactoringRefactoring
Refactoring
 
Spreadsheets: Functional Programming for the Masses
Spreadsheets: Functional Programming for the MassesSpreadsheets: Functional Programming for the Masses
Spreadsheets: Functional Programming for the Masses
 
Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.Proto
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patterns
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
Functional Programming in R
Functional Programming in RFunctional Programming in R
Functional Programming in R
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 

Recently uploaded

[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Recently uploaded (20)

[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

An Introduction to Functional Programming at the Jozi Java User Group

  • 1. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? An Introduction to Functional Programming Andreas Pauley – @apauley Jozi JUG July 28, 2014
  • 2. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? @lambdaluminary We meet once a month, on the second Monday of the month. http://www.meetup.com/lambda-luminaries/
  • 3. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Jemstep Retirement portfolio analysis in Scala. http://www.jemstep.com/
  • 4. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
  • 5. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Who likes FP? “ And that’s why I think functional programming is a natural successor to object-oriented programming. ” — Dave Thomas, Pragmatic Programmers [2] “ Without understanding functional programming, you can’t invent MapReduce ” — Joel Spolsky [3] “ ...it’s almost certainly true that functional programming is the next big thing. ” — Uncle Bob Martin [4]
  • 6. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? “ No matter what language you work in, programming in a functional style provides benefits. You should do it whenever it is convenient, and you should think hard about the decision when it isn’t convenient. ” — John Carmack, ID Software [5]
  • 7. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? But what exactly is “Functional Programming”?
  • 8. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A simple programming example Say I give you an array of integers, and I want every one of them doubled. How would you write it?
  • 9. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A simple programming example I have this: [1,3,6] I want this: [2,6,12]
  • 10. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A simple programming example public static void doubleAll(int[] numbers) { for (int i=0; i < numbers.length; i++) { numbers[i] = numbers[i] * 2; } }
  • 11. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A simple programming example Sorry, I forgot to mention that you cannot do in-place mutation on the list of numbers I give you. Please try again.
  • 12. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A simple programming example Our first try had a void return type: public static void doubleAll(int[] numbers) { for (int i=0; i < numbers.length; i++) { numbers[i] = numbers[i] * 2; } } Now we have to return a result: public static int[] doubleAll(int[] numbers) { int[] nums2 = new int[numbers.length]; for (int i=0; i < numbers.length; i++) { nums2[i] = numbers[i] * 2; } return nums2; }
  • 13. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A simple programming example Looking much better, but you can’t mutate any collection, appending to the new array won’t work. Also, you can’t vary your variables (i++). Please try again.
  • 14. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A simple programming example ??? public static int[] doubleAll(int[] numbers) { int[] nums2 = new int[numbers.length]; for (int i=0; i < numbers.length; i++) { nums2[i] = numbers[i] * 2; } return nums2; }
  • 15. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Let’s try giving a definition of Functional Programming
  • 16. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Functional Programming, noun: Functional Programming is a list of things you CAN’T do. [10]
  • 17. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? You can’t vary your variables 1> X = 42. 42 2> X = X + 1. ** exception error: no match of right hand side value 43
  • 18. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? No while/for loops. Sorry :-( int i; for (i=1; i<=3; i++) { System.out.println(i); }
  • 19. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? You can’t mutate/change your data structures Python >>> list1 = [1,2,3] >>> list2 = list1 >>> print list1.reverse() None >>> list1 [3, 2, 1] >>> list2 [3, 2, 1] Haskell > let list1 = [1,2,3] > let list2 = list1 > reverse(list1) [3,2,1] > list1 [1,2,3] > list2 [1,2,3]
  • 20. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? You can’t have any side e↵ects
  • 21. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Are you kidding me? How can anyone program like this???
  • 22. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? GOTO 10 This sounds like “You can’t have GOTO statements” See Hughes and Dijkstra [1, 6]
  • 23. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? It’s not about what we cannot do.
  • 24. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? We need a better definition of Functional Programming.
  • 25. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Programming Paradigms (Very Simplified) Imperative Declarative
  • 26. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Functional Programming, noun: “ Functional programming is so called because a program consists entirely of functions. ” — John Hughes, Why Functional Programming Matters [1, p. 1]
  • 27. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? OK... so what exactly is a function?
  • 28. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? An example function f(x) = 2x2 2x + 3 1 1 2 3 4 6 8 10 12 14 x y
  • 29. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Variables in functions f(x) = 2x2 2x + 3 When we evaluate the function: f(2) = 8 4 + 3 = 7 • The value of x will not change inside the function body.
  • 30. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Variables in functions f(x) = 2x2 2x + 3 When we evaluate the function: f(2) = 8 4 + 3 = 7 • The value of x will not change inside the function body. • Same input, same output. Every time. (Referential Transparency)
  • 31. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Variables in functions f(x) = 2x2 2x + 3 When we evaluate the function: f(2) = 8 4 + 3 = 7 • The value of x will not change inside the function body. • Same input, same output. Every time. (Referential Transparency) • We can call f multiple times without any side e↵ects.
  • 32. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Variables in functions f(x) = 2x2 2x + 3 When we evaluate the function: f(2) = 8 4 + 3 = 7 • The value of x will not change inside the function body. • Same input, same output. Every time. (Referential Transparency) • We can call f multiple times without any side e↵ects. • We don’t have to recalculate f(2), we can replace any occurrence of f(2) with 7.
  • 33. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Varying variables does not make sense x = x + 1 x x = 1 0 = 1 ) x 6= x + 1
  • 34. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Values are functions Constant values are just functions with no input parameters x = 42 Python function definition: def x(): return 42 Haskell function definition: x = 42
  • 35. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Functions can be composed h(x) = (f g)(x) = f(g(x)) or h = f g
  • 36. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Higher-order Functions Functions can take functions as input. Functions can return functions as the result. h(f, g, x) = f(x) + g(2)
  • 37. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Higher-order Functions The derivative of f(x) returns another function. f(x) = 2x2 2x + 3 d dxf(x) = 4x 2 1 1 2 3 5 10 15 x y
  • 38. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A functional program consists entirely of functions def main(): time = datetime.now() args = sys.argv[1:] print outputString(time, args) def outputString(time, args): return str(time) + " " + joinArgs(args) def joinArgs(args): return "-".join(args) $ ./justfunctions.py Hello from Python 2014-02-15 10:36:42.062697 Hello-from-Python
  • 39. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? A functional program consists entirely of functions main :: IO() main = do time <- getCurrentTime args <- getArgs putStrLn (outputString time args) outputString :: UTCTime -> [String] -> String outputString time args = show(time) ++ " " ++ joinArgs(args) joinArgs :: [String] -> String joinArgs = intercalate "-" $ ./justfunctions Hello from Haskell 2014-02-15 08:36:50.822728 UTC Hello-from-Haskell
  • 40. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Some Haskell Syntax Python: def outputString(time, args): return str(time) + " " + joinArgs(args) Haskell: outputString :: UTCTime -> [String] -> String outputString time args = show(time) ++ " " ++ joinArgs(args)
  • 41. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Recursive function: Haskell doubleAll :: [Int] -> [Int] doubleAll [] = [] doubleAll (x:xs) = x*2 : doubleAll xs Example use in the interactive interpreter: Prelude Main> doubleAll [8,2,3] [16,4,6]
  • 42. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Recursive function expanded doubleAll [] = [] doubleAll (x:xs) = x*2 : doubleAll xs doubleAll [8,2,3] 16 : (doubleAll [2,3]) 16 : 4 : (doubleAll [3]) 16 : 4 : 6 : (doubleAll []) 16 : 4 : 6 : [] 16 : 4 : [6] 16 : [4,6] [16,4,6]
  • 43. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? 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]
  • 44. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Pattern Matching: Haskell doubleAll :: [Int] -> [Int] doubleAll [] = [] doubleAll (x:xs) = x*2 : doubleAll xs
  • 45. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Higher-order Functions 3 Basic List Operations Map Convert each element of a list into some other value.
  • 46. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Higher-order Functions 3 Basic List Operations Map Convert each element of a list into some other value. Filter Get a subset of a list based on some condition.
  • 47. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Higher-order Functions 3 Basic List Operations Map Convert each element of a list into some other value. Filter Get a subset of a list based on some condition. Fold Reduce a list of items to a single value.
  • 48. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Map Apply a function to each element of a list, and you get a new list. a1 a2 a3 ... an b1 b2 b3 ... bn f(a1) f(an)
  • 49. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Map doubleAll :: Num a => [a] -> [a] doubleAll = map (*2) 8 2 3 16 4 6 ⇤2 ⇤2 ⇤2
  • 50. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Account Data data Bank = ABSA | Capitec | FNB | Nedbank | SBSA data Account = Account {bank :: Bank, accNum :: String, owner :: String, balance :: Amount}
  • 51. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Account Data [Account {accNum="4076814233", owner="J. Doe", balance=(Amount 123000.23), bank=ABSA}, Account {accNum="6868773585", owner="J. Black", balance=(Amount 5782347.99), bank=FNB}, Account {accNum="4055892156", owner="A. Kay", balance=(Amount 100), bank=ABSA}, Account {accNum="6584539813", owner="S. Jones", balance=(Amount 2937361.45), bank=FNB}]
  • 52. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Map Map on account data: balances :: [Account] -> [Amount] balances accounts = map balance accounts acc1 acc2 acc3 acc4 acc5 bal1 bal2 bal3 bal4 bal5 balance(acc1) balance(acc5)
  • 53. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Filter acc1 acc2 acc3 acc4 acc5 acc1 acc3 acc5 in? in? in? in? in?
  • 54. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Filter Filter on account data: topAccounts :: [Account] -> [Account] topAccounts accounts = filter isRich accounts isRich :: Account -> Bool isRich acc = balance acc >= (Amount 1000000) Output: *Main> topAccounts accounts [FNB 6868773585 (J. Black) R5782347.99, FNB 6584539813 (S. Jones) R2937361.45]
  • 55. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Fold/Reduce/Inject foldl (+) 0 [8,2,3] 13 0 8 2 3 8 2 3 10 3 13
  • 56. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Fold/Reduce/Inject balanceSum :: [Account] -> Amount balanceSum accounts = foldl (+) 0 (balances accounts) 0 bal1 bal2 bal3 sum bal2 bal3 sum bal3 sum
  • 57. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Function Composition balanceSum :: [Account] -> Amount balanceSum accounts = foldl (+) 0 (balances accounts) 0 bal1 bal2 bal3 sum bal2 bal3 sum bal3 sum s2 :: [Account] -> Amount s2 = balances |> (foldl(+)0) h(x) = (f g)(x) = f(g(x)) h = f g s3 = f1 balances s3 :: [Account] -> Amount s3 = (foldl(+)0) . balances
  • 58. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? balancesPerBank foldl insertBalance Map.empty accounts {} acc1 acc2 acc3 map acc2 acc3 map acc3 map
  • 59. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Fold type BankMap = Map Bank Amount balancesPerBank :: [Account] -> BankMap balancesPerBank = foldl insertBalance Map.empty Output: *Main> balancesPerBank accounts fromList [(ABSA,R123100.23),(FNB,R8719709.44)]
  • 60. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Fold type BankMap = Map Bank Amount balancesPerBank :: [Account] -> BankMap balancesPerBank = foldl insertBalance Map.empty insertBalance :: BankMap -> Account -> BankMap insertBalance bankmap account = Map.insert key value bankmap where key = bank account value = addBalance bankmap account addBalance :: BankMap -> Account -> Amount addBalance bankmap account = case (Map.lookup (bank account) bankmap) of Nothing -> balance account Just bal -> (balance account) + bal
  • 61. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Programming Paradigms (Very Simplified) Imperative Declarative
  • 62. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? In imperative programming: • Your variables can vary any time!
  • 63. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? In imperative programming: • Your variables can vary any time! • You have to use locks to be thread-safe!
  • 64. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? In imperative programming: • Your variables can vary any time! • You have to use locks to be thread-safe! • You have to write your own loops for the most basic list operations!
  • 65. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? In imperative programming: • Your variables can vary any time! • You have to use locks to be thread-safe! • You have to write your own loops for the most basic list operations! • Your data structures are mutable!
  • 66. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? In imperative programming: • Your variables can vary any time! • You have to use locks to be thread-safe! • You have to write your own loops for the most basic list operations! • Your data structures are mutable! • You have to defensively make copies of data to prevent bugs!
  • 67. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? In imperative programming: • Your variables can vary any time! • You have to use locks to be thread-safe! • You have to write your own loops for the most basic list operations! • Your data structures are mutable! • You have to defensively make copies of data to prevent bugs! • You have to defensively check for null values!
  • 68. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? In imperative programming: • Your variables can vary any time! • You have to use locks to be thread-safe! • You have to write your own loops for the most basic list operations! • Your data structures are mutable! • You have to defensively make copies of data to prevent bugs! • You have to defensively check for null values! • You have to think about implicit state! (this, self)
  • 69. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? In imperative programming: • Your variables can vary any time! • You have to use locks to be thread-safe! • You have to write your own loops for the most basic list operations! • Your data structures are mutable! • You have to defensively make copies of data to prevent bugs! • You have to defensively check for null values! • You have to think about implicit state! (this, self) • Code is generally riddled with side e↵ects!
  • 70. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Are you kidding me? How can anyone program like this???
  • 71. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what?
  • 72. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Unit tests Start writing the unit tests for your existing code in a functional programming language
  • 73. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Join the anti-for campaign Less loops, more map/filter/fold http://weblogs.asp.net/podwysocki/archive/2009/06/26/ the-anti-for-campaign.aspx
  • 74. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Treat side e↵ects as a first-class concern
  • 75. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Learn a functional language “ A language that doesn’t a↵ect the way you think about programming, is not worth knowing. ” — Alan Perlis[8]
  • 76. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Disclaim your inheritance Write non-trivial code without using objects and inheritance. Get re-usability with higher-order functions. Try to minimise moving parts instead of encapsulating moving parts. [7]
  • 77. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Join our group @lambdaluminary We meet once a month, on the second Monday of the month. http://www.meetup.com/lambda-luminaries/
  • 78. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Get out of your comfort zone Functional Programming is unfamiliar territory for most. “ If you want everything to be familiar you will never learn anything new. ” — Rich Hickey, author of Clojure[9]
  • 79. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Companies In South Africa Jemstep, Sandton Using Scala for Fund Analysis Allan Gray, Cape Town Using Scala for backend logic and system integration. Yuppiechef, Cape Town Using Clojure for their Warehouse Management System. Cognician, Cape Town Using Clojure to create coaching/learning modules. Eldo Energy, Johannesburg Using Clojure for automated meter reading and intelligent monitoring of consumer energy. Rheo Systems, Pretoria Using Clojure for supply chain integration.
  • 80. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Companies In South Africa Pattern Matched Technologies, Midrand Using Erlang for all systems, eg. processing high volumes of financial transactions. E↵ective Control Systems, Kyalami Using Erlang for printer management. Mira Networks, Somerset West Using Erlang for billing administration and mobile development. Kotive Using Scala for designing workflow processes.
  • 81. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Online Courses Functional Thinking by Neal Ford O’ Reilly http://shop.oreilly.com/product/0636920030393.do Functional Programming Principles in Scala EPFL University https://www.coursera.org/course/progfun School of Haskell FP Complete https://www.fpcomplete.com/school Programming Languages University of Washington https://www.coursera.org/course/proglang
  • 82. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? Books Miran Lipovaˇca Learn You a Haskell for Great Good! http://learnyouahaskell.com/ Fred H´ebert Learn You Some Erlang for Great Good! http://learnyousomeerlang.com/ Yaron Minski, Anil Madhavapeddy, Jason Hickey Real World OCaml https://realworldocaml.org/ Paul Chiusano, R´unar Bjarnason Functional Programming in Scala http://www.manning.com/bjarnason/
  • 83. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? References I John Hughes Why Functional Programming Matters http://www.cs.kent.ac.uk/people/staff/dat/miranda/ whyfp90.pdf Dave Thomas Programming Elixir, A Gentle Introduction http://theprosegarden.com/part-1-of/ Joel Spolsky Can Your Programming Language Do This? http: //www.joelonsoftware.com/items/2006/08/01.html
  • 84. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? References II Robert Martin Functional Programming Basics http://pragprog.com/magazines/2013-01/ functional-programming-basics John Carmack Functional Programming in C++ http://www.altdevblogaday.com/2012/04/26/ functional-programming-in-c/ Edsger W. Dijkstra Go To Statement Considered Harmful http://www.u.arizona.edu/~rubinson/copyright_ violations/Go_To_Considered_Harmful.html
  • 85. Introduction Definition Function Recap Common Idioms Imperative Comparison Challenges! Industry Use Now what? References III Tweet by Michael Feathers https://twitter.com/mfeathers/status/29581296216 Alan Jay Perlis http://www.cs.yale.edu/quotes.html Rich Hickey http: //www.infoq.com/presentations/Simple-Made-Easy Andreas Pauley An Introduction to Functional Programming https://github.com/apauley/fp_presentation