r/functionalprogramming • u/Level_Fennel8071 • Apr 21 '25
Question mutable concept confusion
hello,FP newcomer here, is this considered to be functional? if not how can we implement global state in any application.a good resources that explain this part is appreciated
// Pure function to "increment" the counter
const increment = (count) => count + 1;
// Pure function to "decrement" the counter
const decrement = (count) => count - 1;
// Pure function to "reset" the counter
const reset = () => 0;
// Example usage:
let count = 0;
count = increment(count); // count is now 1
count = increment(count); // count is now 2
count = decrement(count); // count is now 1
count = reset(); // count is now 0
10
Upvotes
10
u/mister_drgn Apr 21 '25
These functions are “pure,” which means they return a new value without producing any side effects, such as changing the value that was passed to them. Pure functions are one typical feature of functional programming. Beyond that, you can’t really talk about whether the code is in a functional style because it doesn’t do anything.
EDIT: Changing the value of the “count” variable repeatedly is not typical of functional programming, though some languages allow it.
6
u/P3riapsis Apr 22 '25
Global state is intentionally avoided in functional programming. A pure function depends only on its inputs, and if you want its output to depend on something else, you make that thing an input to your function.
If you want mutability, you can mimic it with the state monad, or in some cases (like the one you've got here) just reassign a variable to different expressions (here, you'd put "let" before all of the "counter = ..." lines, which would bring the previous value out of scope, and the new value to the name "counter")
3
u/buzzon Apr 22 '25
It would be more idiomatic:
2
u/DogeGode Apr 22 '25
The Elm Architecture is one approach to state handling in functional programming – and an exceptionally useful one at that!