The John the Statistician example code does not show functional programming, because when you do functional programming, the key is that the code is NOT record = thingConstructor(t) is the destination) and it has NO SIDE EFFECTS ( localMap.put(record) - statement with a side effect). As a result of these two restrictions, everything that the function performs is completely captured by its arguments and return value. Rewriting the statistical code as it would have looked if you wanted to emulate a functional language using C ++:
RT getOrCreate (const T thing,
const Function <RT <T>> thingConstructor,
const Map <T, RT <T>> localMap) {
return localMap.contains (t)?
localMap.get (t):
localMap.put (t, thingConstructor (t));
}
As a result of the rule of no side effects, each operator is part of the return value (therefore, return comes first ), and each expression is an expression. In languages that provide functional programming, the return keyword is implied, and the if statement behaves like a C ++ ?: Operator.
In addition, everything is unchanged, so localMap.put needs to create a new copy of localMap and return it instead of changing the original localMap , like normal C ++ or Java. Depending on the structure of localMap, a copy may reuse pointers in the original, reducing the amount of data that needs to be copied.
Some of the benefits of functional programming include the fact that functional programs are shorter and it is easier to change a functional program (because there are no hidden global effects to take into account), and it is easier to get a program in the first place.
However, functional programs tend to run slowly (due to all the copying they have to do), and they are not inclined to interact well with other programs, operating systems or operating systems that deal with memory addresses, low-north byte blocks and others machine-specific, broken bits. The degree of non-interaction, as a rule, is inversely correlated with the degree of functional purity and the rigor of the type system.
More popular functional languages have really strict type systems. In OCAML you can’t even mix math with numbers and floating point or use the same operators (+ to add integers, +. To add float). This can be either an advantage or a disadvantage, depending on how highly you rate the possibility of type checking to detect certain types of errors.
Functional languages also have very large runtimes. Haskell is an exception (GHC executables are almost as small as C programs, both at compile time and at run time), but SML, Common Lisp, and Scheme programs always require tons of memory.