DEV Community

Discussion on: The beauty of Functional Programming

Collapse
lukaszahradnik profile image
Lukáš Zahradník

The non recursive myCount is a pure function.

Collapse
Sloan, the sloth mascot
Comment deleted
Collapse
lukaszahradnik profile image
Lukáš Zahradník

Well, it is a pure function.
What is wrong with accessing variables from function scope?

Thread Thread
fannyvieira profile image
Fanny Author

Because it is performing a side effect, by definition, can you write me a example using interation that you agree that is a impure function?

Thread Thread
lukaszahradnik profile image
Lukáš Zahradník

Sure

let result = 0

function myCount() {
  for (let i = 1; i < 10; i++) {
    result += i
  }
  return result
}

There is example of doing side effects by modifying outside scope, which as you stated, makes the function impure.

In your example you aren't accessing "outside" state

Thread Thread
pthreat profile image
pthreat

Agreed

Thread Thread
ivanpierre profile image
Ivan Pierre • Edited on

result is an external state, initialized outside the function. myCount() will give a different response, every time you call it. There's a side effect on i inside the loop.
That's anything except a pure function.

Pure function:

  • Its return value is the same for the same arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams from I/O devices).
  • Its evaluation has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams).
Thread Thread
lukaszahradnik profile image
Lukáš Zahradník

Author asked for example of impure function so it's obvious that my implementation of myCount isn't pure.

Previously we were talking about authors implementation of myCount which was in the original article and she claimed, that it's not pure, but in reality it was pure.

Collapse
ekoutanov profile image
Emil Koutanov • Edited on

Sorry Fanny, but it would be classed as a pure function in spite of writing to a local variable. As long as the write has no side effects that are externally observable, it would satisfy the definition of a pure function.

Even a recursive function with no visible variable assignment may introduce any number of intermediate variables as part of compiler optimisation; this wouldn't make it any less pure provided these changes did not escape outside function scope.