Functional programming
From Wikipedia :
Functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data
There are some important aspect in functional programming that we should understand.
-
Pure functions
- it’s a term to describe a function that will always return the same output given the same output
- it’s stable, consistent, testable and predictable.
- pure functions never cause side effects or how we can minimize side effects as much as possible.
-
Immutability
- On functional programming, when the data is immutable, it state cannot be changed after its created. If you want to modify, you need to create new object.
- First class functions
When we do functional programming, we must think like we do math. In math, we could define function like this: f(x) = y
We read that function like so: a function that takes x as an input and produces y as an output.
There are term such as higher-order functions which means a function that takes function as an input and return another function as the output. Closest example I could get is map(), filter(), reduce()
When we could define pure functions, we could achieve function composition. Two important techniques we could learn to achieve functional composition is currying and partial application
-
Currying
- It’s a term to describe the process of transforming function with multiple arguments into sequence of function with each one only takes an argument.
- add example of currying practices
-
Partial applications
- In partial applications, we bind some arguments to the functions without fully evaluating it.
- Let’s say we have this functions
func add(_ x: Int) -> (_ y: Int) -> Int {
{ y in return x + y }
}
// bind some functions arguments
let addByTwo = add(2)
// so if we have array like so
let numbers = [1, 3, 5, 7, 9]
// we could transform them
numbers.map(addByTwo)
// output: [3, 5, 7, 9, 11]
References
- An Introduction to the basic principles of Functional Programming
- How to deal with dirty side effects in your pure functional JavaScript
- Functions in Swift: Pure, Higher-Order and First-Class Functions, Currying and Partial Application
- Higher-Order Functions :: Eloquent JavaScript
- Higher Order Functions - Learn You a Haskell for Great Good!