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

2

u/cballowe Nov 23 '23

Recursive functions don't necessarily consume stack. This would depend on language, compiler/interpreter, etc. Many languages could engage some form of tail call optimization to effectively turn it into a loop at the machine code level.

One coding question I used to ask in interviews had a recursive solution and I'd ask candidates "what happens/how would you deal with a really large number of nodes" - the only person who suggested that maybe tail call optimization would help was actually using a language that can't do it (java), but most would just write the loop. I had tested that c/c++ compilers will all happily do the optimization and the generated assembly for recursive and loop was the same. Languages closer to pure functional like Haskell are pretty good at those kinds of optimizations.