SlideShare a Scribd company logo
1 of 30
Download to read offline
What is functional programming?
Functional programming in R
Wrap-up
Functional Programming in R
David Springate
@datajujitsu
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Outline
1 What is functional programming?
2 Elements of functional programming
3 Functional Programming in R
4 A Functional-style generic bootstrap
5 Wrap-up and further reading
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
What is functional programming?
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Programming metaphysics
Programs are representations of reality in a computer
There are different ways to represent reality. . .
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
OOP / imperative metaphysics
C, Python, Java etc.
Everything is an object with state and behaviour
A river is an object with
various attributes bound
to it:
Flow rate
Depth
Pollution levels
Salinity
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Functional Metaphysics
No man ever steps in the same river twice, for it’s
not the same river and he’s not the same man. -
Heraclitus
Lisp, Haskell, F#, Clojure etc.
Things are collections of fixed values which
go through processes (functions) over time
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Elements of Functional Programming
1 Functions as first class citizens
2 Vectorised / declarative expressions
3 “Pure” functions - No side effects
4 Anonymous functions
5 Immutability
6 Recursion
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Functional programming in R
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
R Genealogy
S
Scheme
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
R is a strongly functional language
. . . everything is a function call!
> 1 + 2
## [1] 3
. . . is the same as. . .
> ‘+‘(1, 2)
## [1] 3
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
R is a strongly functional language
. . . everything is a function call!
> 1:10
## [1] 1 2 3 4 5 6 7 8 9 10
. . . is the same as. . .
> ‘:‘(1, 10)
## [1] 1 2 3 4 5 6 7 8 9 10
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Vectorised functions
Are functions that operate on vectors/matrices/dataframes as well
as on single numbers
Often much faster than looping over a vector
Higher level - less to debug!
Very deep in the language
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Vectorised functions
Get all even numbers up to 200000
> # C style vector allocation:
> x <- c()
> for(i in 1:200000){
+ if(i %% 2 == 0){
+ x <- c(x, i)
+ }
+ }
## user system elapsed
## 9.86 0.00 9.88
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Vectorised functions
Get all even numbers up to 200000
> # FP style vectorised operation
> a <- 1:200000
> x <- a[a %% 2 == 0]
## user system elapsed
## 0.01 0.00 0.01
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Vectorised functions
Most built-in functions are vectorised:
> # e.g.
> paste()
> colMeans()
> rowSums()
> log()
> sqrt()
> x > y
> is.na()
> ifelse()
> rnorm() # etc. etc.
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Higher-order functions
. . . Are functions that operate on all elements of a collection
(vector/list/vector/matrix/dataframe)
Function to be applied to each element in turn
In[1] In[2] In[3] In[5]In[4]
Out[1] Out[2] Out[3] Out[5]Out[4]
Input
collection
Output
collection
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Higher-order functions
You just need to think about what goes in and what you want to
come out:
lapply : Any collection -> FUNCTION -> list
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Higher-order functions
You just need to think about what goes in and what you want to
come out:
lapply : Any collection -> FUNCTION -> list
sapply : Any collection -> FUNCTION -> matrix/vector
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Higher-order functions
You just need to think about what goes in and what you want to
come out:
lapply : Any collection -> FUNCTION -> list
sapply : Any collection -> FUNCTION -> matrix/vector
apply : Matrix/dataframe + margin -> FUNCTION ->
matrix/vector
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Higher-order functions
You just need to think about what goes in and what you want to
come out:
lapply : Any collection -> FUNCTION -> list
sapply : Any collection -> FUNCTION -> matrix/vector
apply : Matrix/dataframe + margin -> FUNCTION ->
matrix/vector
Reduce : Any collection -> FUNCTION -> single element
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Closures
An object is data with functions. A closure is a function with data.
- John D Cook
Function data1
Returns
New function
enclosing data
data
data2
Arguments to function
data2
Can build functions that
return new functions:
Useful if some work
only needs to be done
once, when the
function is generated
Great for optimisation
and randomisation
problems
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
An FP-style Bootstrapping function
A Generic function to sample linear models with replacement
Illustrates:
Functions returning new functions
Higher-order functions
Anonymous functions
Vectorised functions
Will test using the iris data: data(iris)
c.f. a non-FP version of the same function
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
An FP-style Bootstrapping function
boot_lm <- function(formula, data, ...){
function(){
lm(formula=formula,
data=data[sample(nrow(data), replace=TRUE),], ...)
}
}
iris_boot <- boot_lm(Sepal.Length ~ Petal.Length, iris)
bstrap <- sapply(X=1:1000,
FUN=function(x) iris_boot()$coef)
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
An FP-style Bootstrapping function
apply(bstrap, MARGIN=1, FUN=quantile,
probs=c(0.025, 0.5, 0.975))
## (Intercept) Petal.Length
## 2.5% 4.155 0.3696
## 50% 4.314 0.4072
## 97.5% 4.458 0.4455
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
A Non-FP-style Bootstrapping function
boot_lm_nf <- function(d, form, iters, output, ...){
for(i in 1:iters){
x <- lm(formula=form,
data=d[sample(nrow(d),
replace = TRUE),], ...)[[output]]
if(i == 1){
bootstrap <- matrix(data=NA, nrow=iters,
ncol=length(x),
dimnames=list(NULL,names(x)))
bootstrap[i,] <- x
} else bootstrap[i,] <- x
}
bootstrap
}
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
A Non-FP-style Bootstrapping function
bstrap2 <- boot_lm_nf(d=iris,
form=Sepal.Length ~ Petal.Length,
iters=1000, output="coefficients")
CIs <- c(0.025, 0.5, 0.975)
cbind( "(Intercept)"=quantile(bstrap2[,1],probs = CIs),
"Petal.Length"=quantile(bstrap2[,2],probs = CIs))
## (Intercept) Petal.Length
## 2.5% 4.167 0.3711
## 50% 4.309 0.4093
## 97.5% 4.447 0.4460
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Wrap-up
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Advantages of Functional Programming
Functional programming in R is
More concise
Often faster
Easier to read and debug
More elegant
Higher level
Truer to the language!
. . . than non-fp
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Further reading
Functional Programming
mitpress.mit.edu/sicp
Functional programming in R
github.com/hadley/devtools/wiki
www.burns-stat.com/pages/Tutor/R_inferno.pdf
Vectorisation
Programming language metaphysics
http://www.infoq.com/presentations/
Are-We-There-Yet-Rich-Hickey
David Springate Functional Programming in R
What is functional programming?
Functional programming in R
Wrap-up
Thank you
github.com/DASpringate
linkedin.com/in/daspringate/
@datajujitsu
daspringate@gmail
. . . Any questions?
David Springate Functional Programming in R

More Related Content

What's hot

RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programmingYanchang Zhao
 
2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factorskrishna singh
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Guy Lebanon
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RRsquared Academy
 
Introduction To R Language
Introduction To R LanguageIntroduction To R Language
Introduction To R LanguageGaurang Dobariya
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3Megha V
 
R Programming Language
R Programming LanguageR Programming Language
R Programming LanguageNareshKarela1
 
Presentation R basic teaching module
Presentation R basic teaching modulePresentation R basic teaching module
Presentation R basic teaching moduleSander Timmer
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: NotesRoberto Casadei
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311Andreas Pauley
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programmingNimrita Koul
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURESUsha Mahalingam
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine LearningAmanBhalla14
 

What's hot (20)

RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programming
 
2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)
 
R programming by ganesh kavhar
R programming by ganesh kavharR programming by ganesh kavhar
R programming by ganesh kavhar
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In R
 
Introduction To R Language
Introduction To R LanguageIntroduction To R Language
Introduction To R Language
 
Inroduction to r
Inroduction to rInroduction to r
Inroduction to r
 
Data Management in Python
Data Management in PythonData Management in Python
Data Management in Python
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
 
R Programming Language
R Programming LanguageR Programming Language
R Programming Language
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
 
Language R
Language RLanguage R
Language R
 
Presentation R basic teaching module
Presentation R basic teaching modulePresentation R basic teaching module
Presentation R basic teaching module
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine Learning
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 

Similar to Functional Programming in R

Similar to Functional Programming in R (20)

F# and the DLR
F# and the DLRF# and the DLR
F# and the DLR
 
Get started with R lang
Get started with R langGet started with R lang
Get started with R lang
 
Lecture1
Lecture1Lecture1
Lecture1
 
1_Introduction.pptx
1_Introduction.pptx1_Introduction.pptx
1_Introduction.pptx
 
Fp for the oo programmer
Fp for the oo programmerFp for the oo programmer
Fp for the oo programmer
 
Presentation
PresentationPresentation
Presentation
 
R basics for MBA Students[1].pptx
R basics for MBA Students[1].pptxR basics for MBA Students[1].pptx
R basics for MBA Students[1].pptx
 
R basics
R basicsR basics
R basics
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with R
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
 
Special topics in finance lecture 2
Special topics in finance   lecture 2Special topics in finance   lecture 2
Special topics in finance lecture 2
 
F# Ignite - DNAD2010
F# Ignite - DNAD2010F# Ignite - DNAD2010
F# Ignite - DNAD2010
 
FULL R PROGRAMMING METERIAL_2.pdf
FULL R PROGRAMMING METERIAL_2.pdfFULL R PROGRAMMING METERIAL_2.pdf
FULL R PROGRAMMING METERIAL_2.pdf
 
R programming Language
R programming LanguageR programming Language
R programming Language
 
FUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptxFUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptx
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
 
R and Python, A Code Demo
R and Python, A Code DemoR and Python, A Code Demo
R and Python, A Code Demo
 
The SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and ComputationThe SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and Computation
 
Functional reactive programming
Functional reactive programmingFunctional reactive programming
Functional reactive programming
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 

Recently uploaded

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
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
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
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
 

Recently uploaded (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
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
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
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
 

Functional Programming in R

  • 1. What is functional programming? Functional programming in R Wrap-up Functional Programming in R David Springate @datajujitsu David Springate Functional Programming in R
  • 2. What is functional programming? Functional programming in R Wrap-up Outline 1 What is functional programming? 2 Elements of functional programming 3 Functional Programming in R 4 A Functional-style generic bootstrap 5 Wrap-up and further reading David Springate Functional Programming in R
  • 3. What is functional programming? Functional programming in R Wrap-up What is functional programming? David Springate Functional Programming in R
  • 4. What is functional programming? Functional programming in R Wrap-up Programming metaphysics Programs are representations of reality in a computer There are different ways to represent reality. . . David Springate Functional Programming in R
  • 5. What is functional programming? Functional programming in R Wrap-up OOP / imperative metaphysics C, Python, Java etc. Everything is an object with state and behaviour A river is an object with various attributes bound to it: Flow rate Depth Pollution levels Salinity David Springate Functional Programming in R
  • 6. What is functional programming? Functional programming in R Wrap-up Functional Metaphysics No man ever steps in the same river twice, for it’s not the same river and he’s not the same man. - Heraclitus Lisp, Haskell, F#, Clojure etc. Things are collections of fixed values which go through processes (functions) over time David Springate Functional Programming in R
  • 7. What is functional programming? Functional programming in R Wrap-up Elements of Functional Programming 1 Functions as first class citizens 2 Vectorised / declarative expressions 3 “Pure” functions - No side effects 4 Anonymous functions 5 Immutability 6 Recursion David Springate Functional Programming in R
  • 8. What is functional programming? Functional programming in R Wrap-up Functional programming in R David Springate Functional Programming in R
  • 9. What is functional programming? Functional programming in R Wrap-up R Genealogy S Scheme David Springate Functional Programming in R
  • 10. What is functional programming? Functional programming in R Wrap-up R is a strongly functional language . . . everything is a function call! > 1 + 2 ## [1] 3 . . . is the same as. . . > ‘+‘(1, 2) ## [1] 3 David Springate Functional Programming in R
  • 11. What is functional programming? Functional programming in R Wrap-up R is a strongly functional language . . . everything is a function call! > 1:10 ## [1] 1 2 3 4 5 6 7 8 9 10 . . . is the same as. . . > ‘:‘(1, 10) ## [1] 1 2 3 4 5 6 7 8 9 10 David Springate Functional Programming in R
  • 12. What is functional programming? Functional programming in R Wrap-up Vectorised functions Are functions that operate on vectors/matrices/dataframes as well as on single numbers Often much faster than looping over a vector Higher level - less to debug! Very deep in the language David Springate Functional Programming in R
  • 13. What is functional programming? Functional programming in R Wrap-up Vectorised functions Get all even numbers up to 200000 > # C style vector allocation: > x <- c() > for(i in 1:200000){ + if(i %% 2 == 0){ + x <- c(x, i) + } + } ## user system elapsed ## 9.86 0.00 9.88 David Springate Functional Programming in R
  • 14. What is functional programming? Functional programming in R Wrap-up Vectorised functions Get all even numbers up to 200000 > # FP style vectorised operation > a <- 1:200000 > x <- a[a %% 2 == 0] ## user system elapsed ## 0.01 0.00 0.01 David Springate Functional Programming in R
  • 15. What is functional programming? Functional programming in R Wrap-up Vectorised functions Most built-in functions are vectorised: > # e.g. > paste() > colMeans() > rowSums() > log() > sqrt() > x > y > is.na() > ifelse() > rnorm() # etc. etc. David Springate Functional Programming in R
  • 16. What is functional programming? Functional programming in R Wrap-up Higher-order functions . . . Are functions that operate on all elements of a collection (vector/list/vector/matrix/dataframe) Function to be applied to each element in turn In[1] In[2] In[3] In[5]In[4] Out[1] Out[2] Out[3] Out[5]Out[4] Input collection Output collection David Springate Functional Programming in R
  • 17. What is functional programming? Functional programming in R Wrap-up Higher-order functions You just need to think about what goes in and what you want to come out: lapply : Any collection -> FUNCTION -> list David Springate Functional Programming in R
  • 18. What is functional programming? Functional programming in R Wrap-up Higher-order functions You just need to think about what goes in and what you want to come out: lapply : Any collection -> FUNCTION -> list sapply : Any collection -> FUNCTION -> matrix/vector David Springate Functional Programming in R
  • 19. What is functional programming? Functional programming in R Wrap-up Higher-order functions You just need to think about what goes in and what you want to come out: lapply : Any collection -> FUNCTION -> list sapply : Any collection -> FUNCTION -> matrix/vector apply : Matrix/dataframe + margin -> FUNCTION -> matrix/vector David Springate Functional Programming in R
  • 20. What is functional programming? Functional programming in R Wrap-up Higher-order functions You just need to think about what goes in and what you want to come out: lapply : Any collection -> FUNCTION -> list sapply : Any collection -> FUNCTION -> matrix/vector apply : Matrix/dataframe + margin -> FUNCTION -> matrix/vector Reduce : Any collection -> FUNCTION -> single element David Springate Functional Programming in R
  • 21. What is functional programming? Functional programming in R Wrap-up Closures An object is data with functions. A closure is a function with data. - John D Cook Function data1 Returns New function enclosing data data data2 Arguments to function data2 Can build functions that return new functions: Useful if some work only needs to be done once, when the function is generated Great for optimisation and randomisation problems David Springate Functional Programming in R
  • 22. What is functional programming? Functional programming in R Wrap-up An FP-style Bootstrapping function A Generic function to sample linear models with replacement Illustrates: Functions returning new functions Higher-order functions Anonymous functions Vectorised functions Will test using the iris data: data(iris) c.f. a non-FP version of the same function David Springate Functional Programming in R
  • 23. What is functional programming? Functional programming in R Wrap-up An FP-style Bootstrapping function boot_lm <- function(formula, data, ...){ function(){ lm(formula=formula, data=data[sample(nrow(data), replace=TRUE),], ...) } } iris_boot <- boot_lm(Sepal.Length ~ Petal.Length, iris) bstrap <- sapply(X=1:1000, FUN=function(x) iris_boot()$coef) David Springate Functional Programming in R
  • 24. What is functional programming? Functional programming in R Wrap-up An FP-style Bootstrapping function apply(bstrap, MARGIN=1, FUN=quantile, probs=c(0.025, 0.5, 0.975)) ## (Intercept) Petal.Length ## 2.5% 4.155 0.3696 ## 50% 4.314 0.4072 ## 97.5% 4.458 0.4455 David Springate Functional Programming in R
  • 25. What is functional programming? Functional programming in R Wrap-up A Non-FP-style Bootstrapping function boot_lm_nf <- function(d, form, iters, output, ...){ for(i in 1:iters){ x <- lm(formula=form, data=d[sample(nrow(d), replace = TRUE),], ...)[[output]] if(i == 1){ bootstrap <- matrix(data=NA, nrow=iters, ncol=length(x), dimnames=list(NULL,names(x))) bootstrap[i,] <- x } else bootstrap[i,] <- x } bootstrap } David Springate Functional Programming in R
  • 26. What is functional programming? Functional programming in R Wrap-up A Non-FP-style Bootstrapping function bstrap2 <- boot_lm_nf(d=iris, form=Sepal.Length ~ Petal.Length, iters=1000, output="coefficients") CIs <- c(0.025, 0.5, 0.975) cbind( "(Intercept)"=quantile(bstrap2[,1],probs = CIs), "Petal.Length"=quantile(bstrap2[,2],probs = CIs)) ## (Intercept) Petal.Length ## 2.5% 4.167 0.3711 ## 50% 4.309 0.4093 ## 97.5% 4.447 0.4460 David Springate Functional Programming in R
  • 27. What is functional programming? Functional programming in R Wrap-up Wrap-up David Springate Functional Programming in R
  • 28. What is functional programming? Functional programming in R Wrap-up Advantages of Functional Programming Functional programming in R is More concise Often faster Easier to read and debug More elegant Higher level Truer to the language! . . . than non-fp David Springate Functional Programming in R
  • 29. What is functional programming? Functional programming in R Wrap-up Further reading Functional Programming mitpress.mit.edu/sicp Functional programming in R github.com/hadley/devtools/wiki www.burns-stat.com/pages/Tutor/R_inferno.pdf Vectorisation Programming language metaphysics http://www.infoq.com/presentations/ Are-We-There-Yet-Rich-Hickey David Springate Functional Programming in R
  • 30. What is functional programming? Functional programming in R Wrap-up Thank you github.com/DASpringate linkedin.com/in/daspringate/ @datajujitsu daspringate@gmail . . . Any questions? David Springate Functional Programming in R