Code
# Pure function: calculates square of a number
square <- function(x) {
x * x
}
square(4) # Returns 16, always for input 4, no side effects[1] 16
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. In R, functional programming is a powerful tool that allows you to write cleaner, more efficient, and more maintainable code.
Functional programming (FP) is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state or mutable data. It emphasizes writing code using pure functions, immutability, and declarative rather than imperative approaches. Below, I’ll break down the core concepts of functional programming and explain how it works, keeping the explanation clear and comprehensive.
square(5) => 25, is pure because it always returns the same result for the same input and doesn’t affect anything else.push, you might use concat to return a new array: [1, 2].concat([3]) => [1, 2, 3], leaving the original array unchanged.map function in JavaScript, which applies a function to each element of an array: [1, 2, 3].map(x => x * 2) => [2, 4, 6].reduce (declarative: [1, 2, 3].reduce((a, b) => a + b, 0)) instead of a loop that explicitly iterates and updates a sum variable (imperative).f(g(x))).double(x) and addOne(x), you can compose them to create a new function: compose(double, addOne)(5) => double(addOne(5)) => double(6) => 12.square(4) always returns 16, you can replace square(4) with 16 anywhere in the code without affecting the outcome.Purely Functional: Haskell, Elm, PureScript.
Multi-Paradigm with FP Support: JavaScript, Python, R, Scala, Clojure, OCaml, F#.
Example in R:
[1] 16
This avoids mutating the original array and uses pure functions (filter and map).
Suppose you’re building a program to process a list of user names and return them in uppercase, sorted alphabetically. In R:
alice bob charlie
"ALICE" "BOB" "CHARLIE"
This code is declarative, uses pure functions, and avoids mutating the original users array.
FP shines in scenarios requiring reliability, concurrency, or complex data transformations. It’s widely used in domains like: - Web Development: Libraries like React encourage FP principles (e.g., immutability, pure components). - Data Processing: Tools like Apache Spark use FP concepts for distributed data transformations. - Financial Systems: Where predictability and correctness are critical.
Functional programming (FP) in R involves leveraging the language’s features to write code that emphasizes pure functions, immutability, first-class functions, and declarative programming. While R is not a purely functional language like Haskell, it supports functional programming through its treatment of functions as first-class objects and libraries like purrr (part of the tidyverse). Below, I’ll explain how to perform functional programming in R, covering key concepts, techniques, and examples, while keeping the explanation practical and concise.
Pure Functions: Functions that always produce the same output for the same input and have no side effects (e.g., no modification of global variables).Immutability: Avoiding changes to data; instead, creating new objects with transformations.First-Class and Higher-Order Functions: Functions can be assigned to variables, passed as arguments, or returned from other functions.Declarative Style: Using functions like map, filter, or reduce to describe transformations rather than imperative loops.Avoiding Side Effects: Minimizing operations like printing or modifying external state within functions.Base R: Provides functional programming constructs like lapply, sapply, apply, Reduce, and anonymous functions. purrr: A tidyverse package that offers a consistent, powerful set of FP tools like map, filter, reduce, and more. magrittr: Provides the pipe operator (%>%) for chaining functions in a readable, declarative way. dplyr: While primarily for data manipulation, it aligns with FP by encouraging immutable transformations.
Functional programming is a powerful paradigm that promotes writing clean, predictable, and modular code by using pure functions, immutability, and declarative techniques. While it has a learning curve and isn’t suited for every problem, its benefits in testability, concurrency, and maintainability make it a valuable approach in modern software development. Languages like Haskell and libraries in JavaScript/Python make it accessible, and its principles can be applied even in non-functional languages to improve code quality.
Wickham, H., & Grolemund, G. (2023). R for Data Science (2nd ed.)
Practical guide to FP with purrr for data science.
https://r4ds.hadley.nz/iteration.html
Wickham, H. (2019). Advanced R (2nd ed.)
In-depth coverage of FP concepts like closures and higher-order functions.
https://adv-r.hadley.nz/functional-programming.html
purrr Package Documentation
Official guide for purrr with map, filter, and reduce examples.
https://purrr.tidyverse.org/
Grolemund, G. (2017). Functional Programming with purrr
RStudio talk on using purrr for FP in data analysis.
Search: “Garrett Grolemund purrr RStudio”
Bryan, J. (2019). Happy Git and GitHub for the useR
FP examples for reproducible data workflows with purrr.
https://happygitwithr.com/