Generic programming: fundamental concepts in C++ template metaprogramming
In Functional programming, loop is not allowed because variable is not mutable. To loop, is to alter counter variables. In Functional programming, recursion is used to accumulate or iterate, in recursion the rule 'immutable variable' is not violated.
A programming construct is a fundamental concept of programming, it's a logical unit. A program is a hierarchical structure of programming constructs. There are 4 basic constructs: sequential, conditional, loop, function (lambda). What a program does is side effect of a program executing these constructs.
1. Sequential construct:
2. What's a conditional construct?
if (condition) then
This construct is allowed in both procedural and functional programming.
3. What's a loop? there are 2 kinds of loops based on its result (not side effect), infinite loop, finite loop. Often a loop can be decomposed into sequential and conditional constructs. For example a infinite loop
condition = true
a finite loop
condition = true
if(result=do B) condition = false // note that the value of condition is altered
In functional programming, variable value is immutable once defined, to rewrite the above example with recursion, we need the help of a function construct.
4. define a function or a lambda
bool result = do B
bool result = do_b
As you can see, no variable value is ever changed after the point of definition (declaration and initialization), a key characteristic of functional programming.
C++ template provides powerful means to do functional programming, interestingly by design it has the same 'immutable variable' requirement. Let's see how we again transform the above example into C++ templates
bool result = do_B;
In summary, conditional is implemented with partial specialization, and loop is implemented with recursion. Why bother doing this? Functional programming as a form of generic programming, provides a higher level of concept correctness through programming logic.