Functional Programming
# Functional
Programming in a functional style often includes using functions as values by passing them in arguments, returning them from other functions, assigning them to variables for later execution, and so forth.
Adapting to that perspective requires letting go of old ideas: assignment statements, loops, classes and objects, among others. That wonāt be easy.A function maps an input to an output; for the same input, it always produces the same output. That is, mathematical functions areĀ stateless: they do not maintain any extra information orĀ stateĀ that persists between usages of the function.
Functions areĀ first-class: you can use them as input to other functions, and produce functions as output. Expressing everything in terms of functions enables a uniform and simple programming model that is easier to reason about than the procedures and methods found in other families of languages.
- No mutable data (no side effect).
- No state (no implicit, hidden state).
- All state is bad?Ā No, theĀ hidden,Ā implicitĀ state is bad.
- Functional programming does not eliminate state, it just makes itĀ visibleĀ andĀ explicitĀ (at least when programmers want it to be).
- Functions areĀ pureĀ functions in the mathematical sense: their output depend only on their inputs, there is no āenvironmentā.
- The same result returned by functions called with the same inputs.
# Properties
- Pattern Matching
- Closures, a function-like construct you can store in a variable
- Iterators, a way of processing a series of elements
# Example
let rec fast_fib n =
let rec helper i pp p =
if i = 0 then pp
else helper (i - 1) (pp + p) p
in
if n = 0 then 0
else helper n 0 1