The main concepts of the functional paradigm are high order functions (functions that receive other functions as arguments) and absence of side effects . Programs are written as function comps, rather than sequential procedures.
To solve this problem, we can define the desired result as the list of numbers that passes a primality test .
We started by generating a list (an array, actually) of candidates:
var candidatos = [];
for (var i = 2; i <= 10000; i++) {
candidatos.push(i);
}
And, of these candidates, we want to separate the passers in a primality test. We defined our test:
var teste_primo = function (n) {
for (var i=2; i*i <= n; i++)
if (n%i == 0)
return false;
return true;
}
And, finally, we filter the candidates who pass the test:
candidatos.filter(teste_primo)
Note that the filter function takes another function as its argument - our primality test. It applies the test to the numbers and returns a new array containing only those passing the test.
We can use the same function, for example, to separate the pairs:
candidatos.filter (function (n) {return n % 2 == 0})
(Note that I defined the function at the same time that I passed it as a parameter - I do not need to give it a name if I use it only once, which is common in the functional paradigm.)
It is important to note that, except for the declaration of our list of candidates, none of our functions have generated side effects (change of external variables, etc.). We define functions and compose these functions to get the result as a return.
Another consequence is that if we want to change our primality test to something more efficient, we just need to provide another function instead of test_primo . The primality test is isolated from the rest of the program logic.
Finally, the filter function is already implemented in the language, but we could implement our own version. What it does is to get an array, a test, and return an array with the elements that pass the test:
var meu_filter = function (arr, teste){
var saida = []
for (var i = 0; i <= arr.length; i++)
if (teste(arr[i])){
saida.push(i)
}
return saida
}
Testing:
< meu_filter(candidatos,teste_primo)
> Array [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 1219 mais… ]