3 ms·
You could have an atom that holds the state and a function which can update that atom. You might do something like the elm architecture where you pass a message
by richeyryan 6y ago
You could have an atom that holds the state and a function which can update that atom. You might do something like the elm architecture where you pass a message to a reducer which produces the new state that the atom is set to. All the logic is contained in the reducer and is pure and immutable and the state change happens at a single controlled point.
- phoe-krk 6y agoOK. If I understood correctly, then you limit the mutable state to one point, and use functional logic everywhere around it. You can also optionally close over the atom to achieve encapsulation. Thanks, TIL! That's equivalent to the "mostly functional" style that's doable in Common Lisp.
- harperlee 6y agoExactly! This method of limiting the mutable part to one point is a pattern that is highly useful, and highly used, when working in clojurescript with react through reagent and re-frame, for example: you represent the whole state of your app in a tree of maps and define functions that, given a version of your app state, return the updated version. Then you just execute state-changing pure functions linked to a stream of events to move your one-point-mutable-app-state through a stream of valid states. (and also obviously functions that map that state to HTML/CSS/SVG/etc.).
- marcofiset 6y agoExactly. Functional programming is pretty much all about being very mindful of when to use state vs pure functions.
- kazinator 6y agoUsing state is not functional programming, so you're really saying that functional programming is all about being mindful when to use functional programming versus when to abandon functional programming.
- richeyryan 6y agoYeah, Clojure is one of those languages where functional purity at all costs isn't really the goal. Like others have said its more about being careful how you set state and Clojure gives you loads of great functions for doing everything in a pure way. Its standard library is its greatest asset as far as I'm concerned
- p_l 6y agoThere's also the added benefit of Software Transactional Memory being available for operations on said mutable state, in case you need to access it from multiple threads.