Skip to content

Instantly share code, notes, and snippets.

@sdiehl
Created January 25, 2012 17:33
Show Gist options
  • Select an option

  • Save sdiehl/1677478 to your computer and use it in GitHub Desktop.

Select an option

Save sdiehl/1677478 to your computer and use it in GitHub Desktop.
The essense of functional programming in R.
# Value of x depends on order foo, bar are called. They have the
# side effect of altering global state so they aren't pure
# functions
x = 0
foo <- function() {
x <<- (x+1)
}
bar <- function() {
x <<- (x+2)
}
# Calling fetch has the side-effect of going out to the web and
# reading a file. Network could be down, the url could fail...
# either way it is not guaranteed to produce the same output every
# time so its not a pure function.
fetch <- function() {
read.csv(url('http://www.cyclismo.org/tutorial/R/simple.csv'))
}
# Higher order functions, functions which return functions.
add <- function(x) {
addf <- function(y) {
return (x+y)
}
}
addOne <- add(1)
print(addOne(5))
### Closures
fizz <- function(x) {
x <- x+1
bang <- function(y) {
y <- x + y
}
}
first = fizz(1)
second = first(2)
third = first(3)
fourth = fizz(1)(1)
print(first)
print(second)
print(third)
print(fourth)
# "map" function, every functional programmers favorite example .
# You can do this natively in R but lets recreate it using
# recursion and higher order functions, because why not. :)
map <- function(f, arr) {
map_ <- function(ar) {
if (length(ar) > 1) {
append( f(ar[1]), map_(ar[(2):length(ar)]) );
} else {
return( f(ar[1]) )
}
}
map_(arr)
}
f = function(x){x %% 3}
print(map(f, c(1:25)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment