4 ms·
Just a note, variables are always replaceable by constants ;-) @tailrec def pow(n: Int, result: Int = 1): Int = if (n > 0) pow(n - 1, result * 2)
by bad_user 11y ago
Just a note, variables are always replaceable by constants ;-)
@tailrec
def pow(n: Int, result: Int = 1): Int =
if (n > 0) pow(n - 1, result * 2)
else result
But yes, mutability isn't problematic if it's well encapsulated. Works well for simple functions, but when you get to more complicated things (e.g. classes/modules) the problem is that proper encapsulation is very hard to do, sometimes next to impossible.
- mafribe 11y agoSure, we can always translate away state and pass it explicitly. Some people find some algorithms can be more naturally expressed using state. (And "some people" is a polite way of saying "alot".) The question of whether state can always be replaced by pure functions without loss of asymptotic complexity is open as of April 2016. All I wanted to point out is that there is no need of becoming a functional Taliban: if state is kept local, that's usually fine. when you get to more complicated things Yes. Then don't use it. My rule of thumb is: definition and all uses of state should be visible to the programmer without scrolling.