What is purity?
Purity for a function is defined as one that will always return the same output for the same input and perform no side e...
For further actions, you may consider blocking this person and/or reporting abuse
I don't think that the
void
return type has anything to to with function purity. A function can be pure even if it returns some value. It just shouldn't modify anything outside of it and does not use any variables that are defined outside of its scope. Its return value should be determined solely by its input parameters.@tuxOr
There is nothing to do with the signature of a function.
A function is pure if and only if
So in your example, assuming
process(var1, var2)
will make some side effect somewhere else in the program, it is not a pure function.However, if
process
do not make any changes, then it will still be a pure function.No.
For example:
This function is not pure as it modifies
a
.Yes I would say that Luka is right.
And would add that for me, making a function that returns void is a way of declaring that that particular function is impure and will most likely be made to do side effects stuff.... cause we need to do them sometimes:)
I think something that returns VOID is not even a function at all, but a procedure....don't functions need input/ouput by mathematical definitions?
This is the working definition that I use.
that is a great way to describe it I think!
Currently this is not valid Javascript:
const addYtoX(x, y) => x + y
But this is:
const addYtoX = (x, y) => x + y
oups! I just corrected that, thanks a lot!
Any useful function returning
void
is definitely impure.Even if it doesn't reference anything besides its parameters, it's still bound to mutate or otherwise bother the parameters.
A pure function:
One of the consequences of 2. is that when given the same parameters, it should always produce the same return value.
This is a useful dipping stick that demonstrates that functions that depend on eg time or randomness aren't pure.
Unfortunately the signature wont make this function pure.
What you would need in this case is
composition
which would allow you to compose 2 functions. I will at one point cover composition, in the mean time, you can read that great article by Eric Elliott --> medium.com/javascript-scene/master...Luka is right. For function to be pure it shouldn't change things out of it's scope too which
void
function can do. It's because whole point of pure functions is to write more predictable code.Funny that you choose JavaScript for the examples, while it doesn't support pure functions.
There is a good article on the topic that seems to spark some interesting debates--> hackernoon.com/do-pure-functions-e...
I feel we can still benefit from the concept and that indeed JavaScript will remain a language full of surprises ;) Maybe that is why we like it so much in the end?
Purity simply means:
If a function returns void and has no side-effects, it's pure, but it also doesn't do anything interesting.