r/functionalprogramming • • Nov 20 '23

Question Is the code still functional programming?

If i declare a variable inside a function and mutate it, is it still considered functional?

For example, if i write a function to find the max of an array with a for loop and a max value and return that max value the function is still pure. It doesn't have any side effects, since the max variable is not global but it does contraddict the principle of immutability of data. So my question is, can you use for loops and variables inside of functions or not?

(ik of another way of getting the result using functions like reduce in javascript, thats not the point of the question)

13 Upvotes

18 comments sorted by

View all comments

Show parent comment

4

u/marcinzh Nov 21 '23

There is practical value to "never using variables ever": it's avoiding bugs by accidental capture.

The ultimate goal is maintaining the property of being "proper" function: called with the same arguments, it must always produce the same result. In some functions using vars internally, this property can be trivially guaranteed. In others, it's not so simple.

And then, refactorings happen.

Rather than "never using variables ever", let it be "avoiding using vars, as much as you can, unless they really, really, REALLY come with substantial benefit, and you 100% know what you're doing".

To me, not using vars is simply a safer policy, rather than having anything to do with being "purist".