The main concepts of the functional paradigm are high-order functions (functions that receive other functions such as arguments) and no side effects. Programs are written as compositions of functions, 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 start 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 those who pass a primality test. We set 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 from the candidates those who pass the test:
candidatos.filter(teste_primo)
Note that the function filter takes as argument another function - our primality test. It applies the test on the numbers and returns a new array containing only those that pass 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 I passed it as a parameter - I don’t 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 generated side effects (alteration of external variables, etc.). We define functions and compose these functions to obtain the result as 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 prime test. The primality test is isolated from the rest of the logic of the program.
Finally, the function filter is already implemented in the language, but we could implement our own version. What it does is receive an array, a test, and returns an array of 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… ]
A little vague the question, no?
– epx