I'm fine with the pure function
concept on pretty simple examples like...
function addTwo(val){
return val + 2;
}
Given the same arguments, it yields the same result, leading to Referential Transparency and good deterministic code.
But then I've came across examples like these (taken from professor frisby mostly adequate guide, but I've found similar examples on other FP JS books)
//pure
var signUp = function(Db, Email, attrs) {
return function() {
var user = saveUser(Db, attrs);
welcomeUser(Email, user);
};
};
var saveUser = function(Db, attrs) {
...
};
var welcomeUser = function(Email, user) {
...
};
and I don't get why isn't considered an external dependency (so, impure) the call to saveUser
or welcomeUser
.
I know that from a function/IO point of view, signUp
always return the "same" (an equivalent) wired function, but it feels weird to me.
It's difficult to me to understand why even
function multiplyBy(times){
return value => value * times;
}
const fiveTimes = multiplyBy(5);
fiveTimes(10);
is considered pure
. From the returned function POV, accesing to times
is a lookup on the scope-chain, it could come from the immediate outer scope, or from beyond (like global scope).
Any one wants to bring some light to this?
times
come from beyond the immediate outer scope?const multiply = ...
(ES2015). Would you still have a question about whetherfiveTimes
was pure? JavaScript isn't primarily a functional language (although it can mostly be used that way), so if the mutability of those identifiers is what's bothering you, the answer might be "by convention until we can use ES2015 we're assuming you leave function identifiers unchanged."multiplyBy
would be something likemultiplyBy:: a -> b -> c
;multiplyBy
takes an argumenta
and returns a function which takes an argumentb
and returns a valuec
. The second one, function which takes ab
, is a type in itself.multiplyBy
creates a new type, a functionb => b * 5
. That's pretty darn pure.