Z
Z
zekohina2016-11-08 21:48:45
Functional programming
zekohina, 2016-11-08 21:48:45

Why not keep the state inside the function?

Let's take the function of finding the maximum number as an example:

function getMaxNumber(numbers) {
  let maxNumber = numbers[0];
  for (let number of numbers) {
  if (number > maxNumber) maxNumber = number;
  }
  return maxNumber;
}


Functional programming preaches that state should not be stored in any form. But why is it bad to store it if it does not give side effects? It's still the same pure function.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Kucherenko, 2016-11-09
@evgenyspace

Bad store in terms of functional programming philosophy . After all, its meaning is in the mathematics of constructions.
The function you have is clean, but it is not in a functional style. Compare:
PS: I'm currently reading a book on FP in JS, I recommend it!

S
Sergey, 2016-11-09
@begemot_sun

In this implementation, the function remains pure, because you do not store any state there.
But if you store state in a function, then the function will not be pure.
You won't be able to test it properly because you'll get different responses for the same input every time.

D
Daniil Kolesnichenko, 2016-11-09
@KolesnichenkoDS

In essence, if the function is pure, then it doesn't matter what's going on inside. If using loops is easier or more productive, write through loops. The main thing is that there are no side effects (including reading / changing the global state). Yes, if you follow the principles of FP 100%, then mutable state should be abandoned altogether, but when programming in imperative languages, no one does this for a number of reasons, including the lack of syntactic sugar in such languages, familiar to functionalists, as well as possible performance problems (it is a question in the core just about use of a recursion instead of cycles, as in your case).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question