Can a pure function call an external method?
for example:
class Dog {
function jump(name) {
return "a dog named " + name + " jumped!"
}
function jumpTwice(names) {
var result = [];
for (var i = 0; i < 2; i++) {
result.push(jump(names[i]));
}
return result.join("\n");
}
}
can jumpTwice()
be considered as a pure function
?
Yes you can do the same to Math. random() if you memoize it making every call to pureRandom return exactly the same number. And this would make pureRandom pure because it always returns the same result. I personally would not call it a "random" function.
A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed. It does not depend on any state or data change during a program's execution. Rather, it only depends on its input arguments.
Calling a function from within itself is called recursion and the simple answer is, yes.
In computer programming, a pure function is a function that has the following properties: the function return values are identical for identical arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams), and.
A pure f
function can call any other function/method g0...gn
.
But g0...gn
must be pure as well.
As soon as you get a pure function f
and you invoke a non pure function g
from within f
, then f
is no longer pure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With