Functional programming in R

Pemrograman Fungsional Tingkat Menengah dengan purrr

Colin Fay

Data Scientist & R Hacker at ThinkR

About computation in R

"To understand computations in R, two slogans are helpful:

- Everything that exists is an object.

- Everything that happens is a function call."    -John Chambers

class(`+`)
"function"
class(`<-`)
"function"
Pemrograman Fungsional Tingkat Menengah dengan purrr

R as a functional programming language

Functions can be

  • manipulated

  • stored in a variable

  • lambda

 

  • stored in a list

  • arguments of a function

  • returned by a function

Pemrograman Fungsional Tingkat Menengah dengan purrr

About "pure functions"

In a pure function:

  • output only depends on input

  • no "side-effect"

# Output depends only on inputs
# No side effect
sum(1:10)
55
mean(1:100)
50.5
Pemrograman Fungsional Tingkat Menengah dengan purrr

Impure functions are useful

Impure functions:

  • Depend on environment

  • Have "side-effects"

# Outputs depends of environment 
Sys.Date()
"2018-10-04"
# Side effect only
write.csv(iris, "iris.csv")
Pemrograman Fungsional Tingkat Menengah dengan purrr

Read more about functional programming

Pemrograman Fungsional Tingkat Menengah dengan purrr

Let's practice!

Pemrograman Fungsional Tingkat Menengah dengan purrr

Preparing Video For Download...