SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programming
Yanchang 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, Factors
krishna singh
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
Khaled Al-Shamaa
 
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 by ganesh kavhar
R programming by ganesh kavharR programming by ganesh kavhar
R programming by ganesh kavhar
Savitribai Phule Pune University
 
R Programming: Mathematical Functions In R
R Programming: Mathematical Functions In RR Programming: Mathematical Functions In R
R Programming: Mathematical Functions In R
Rsquared Academy
 
Introduction To R Language
Introduction To R LanguageIntroduction To R Language
Introduction To R Language
Gaurang Dobariya
 
Inroduction to r
Inroduction to rInroduction to r
Inroduction to r
manikanta361
 
Data Management in Python
Data Management in PythonData Management in Python
Data Management in Python
Sankhya_Analytics
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
Megha V
 
R Programming Language
R Programming LanguageR Programming Language
R Programming Language
NareshKarela1
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
Infinity Tech Solutions
 
Language R
Language RLanguage R
Language R
Girish Khanzode
 
Presentation R basic teaching module
Presentation R basic teaching modulePresentation R basic teaching module
Presentation R basic teaching module
Sander Timmer
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto 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 - 20140311
Andreas Pauley
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
Nimrita Koul
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
Usha Mahalingam
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine Learning
AmanBhalla14
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
Damian T. Gordon
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programming
Yanchang 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, Factors
krishna 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 R
Rsquared Academy
 
Introduction To R Language
Introduction To R LanguageIntroduction To R Language
Introduction To R Language
Gaurang Dobariya
 
Python programming –part 3
Python programming –part 3Python programming –part 3
Python programming –part 3
Megha V
 
R Programming Language
R Programming LanguageR Programming Language
R Programming Language
NareshKarela1
 
Presentation R basic teaching module
Presentation R basic teaching modulePresentation R basic teaching module
Presentation R basic teaching module
Sander Timmer
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto 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 - 20140311
Andreas Pauley
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
Nimrita Koul
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
Usha Mahalingam
 
R programming & Machine Learning
R programming & Machine LearningR programming & Machine Learning
R programming & Machine Learning
AmanBhalla14
 

Similar to Functional Programming in R (20)

F# and the DLR
F# and the DLRF# and the DLR
F# and the DLR
Richard Minerich
 
Unit 1 financial analyticsfsddsdadsdsdsd
Unit 1 financial analyticsfsddsdadsdsdsdUnit 1 financial analyticsfsddsdadsdsdsd
Unit 1 financial analyticsfsddsdadsdsdsd
bchandrasep
 
Get started with R lang
Get started with R langGet started with R lang
Get started with R lang
senthil0809
 
Google Interview Questions By Scholarhat
Google Interview Questions By ScholarhatGoogle Interview Questions By Scholarhat
Google Interview Questions By Scholarhat
Scholarhat
 
Lecture1
Lecture1Lecture1
Lecture1
Sai Jyothendranadh
 
1_Introduction.pptx
1_Introduction.pptx1_Introduction.pptx
1_Introduction.pptx
ranapoonam1
 
Fp for the oo programmer
Fp for the oo programmerFp for the oo programmer
Fp for the oo programmer
Shawn Button
 
Presentation
PresentationPresentation
Presentation
pnathan_logos
 
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
rajalakshmi5921
 
R basics
R basicsR basics
R basics
Sagun Baijal
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with R
Martin Jung
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
Zumba Fitness - Technology Team
 
Special topics in finance lecture 2
Special topics in finance   lecture 2Special topics in finance   lecture 2
Special topics in finance lecture 2
Dr. Muhammad Ali Tirmizi., Ph.D.
 
F# Ignite - DNAD2010
F# Ignite - DNAD2010F# Ignite - DNAD2010
F# Ignite - DNAD2010
Rodrigo Vidal
 
FULL R PROGRAMMING METERIAL_2.pdf
FULL R PROGRAMMING METERIAL_2.pdfFULL R PROGRAMMING METERIAL_2.pdf
FULL R PROGRAMMING METERIAL_2.pdf
attalurilalitha
 
R programming Language
R programming LanguageR programming Language
R programming Language
SarthakBhargava7
 
FUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptxFUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptx
SafnaSaff1
 
What`s New in Java 8
What`s New in Java 8What`s New in Java 8
What`s New in Java 8
Mohsen Zainalpour
 
R and Python, A Code Demo
R and Python, A Code DemoR and Python, A Code Demo
R and Python, A Code Demo
Vineet Jaiswal
 
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
Jean-Jacques Dubray
 
Unit 1 financial analyticsfsddsdadsdsdsd
Unit 1 financial analyticsfsddsdadsdsdsdUnit 1 financial analyticsfsddsdadsdsdsd
Unit 1 financial analyticsfsddsdadsdsdsd
bchandrasep
 
Get started with R lang
Get started with R langGet started with R lang
Get started with R lang
senthil0809
 
Google Interview Questions By Scholarhat
Google Interview Questions By ScholarhatGoogle Interview Questions By Scholarhat
Google Interview Questions By Scholarhat
Scholarhat
 
1_Introduction.pptx
1_Introduction.pptx1_Introduction.pptx
1_Introduction.pptx
ranapoonam1
 
Fp for the oo programmer
Fp for the oo programmerFp for the oo programmer
Fp for the oo programmer
Shawn Button
 
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
rajalakshmi5921
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with R
Martin Jung
 
F# Ignite - DNAD2010
F# Ignite - DNAD2010F# Ignite - DNAD2010
F# Ignite - DNAD2010
Rodrigo Vidal
 
FULL R PROGRAMMING METERIAL_2.pdf
FULL R PROGRAMMING METERIAL_2.pdfFULL R PROGRAMMING METERIAL_2.pdf
FULL R PROGRAMMING METERIAL_2.pdf
attalurilalitha
 
FUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptxFUNCTIONS IN R PROGRAMMING.pptx
FUNCTIONS IN R PROGRAMMING.pptx
SafnaSaff1
 
R and Python, A Code Demo
R and Python, A Code DemoR and Python, A Code Demo
R and Python, A Code Demo
Vineet Jaiswal
 
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
Jean-Jacques Dubray
 
Ad

Recently uploaded (20)

TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Ad

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