Is it possible for pure functions in Haskell to mutate local copies of variables, in the way that clojure can as mentioned in Functional Programming Is A Scam!, by David Nolen? If not what are the reasons for this, and if so are there any examples anyone could point me to?
A similar question was asked in Functions that look pure to callers but internally use mutation and the general consensus seemed to be that it was OK for pure functions to perform mutation, as long as the mutations were performed on local copies of variables (i.e. the effect of the mutation does not escape the function and have a non-local effects).
The question arose when I translated the bubble sort in Shen (Local mutation, global mutation, mutable datastructures, Bubblesort in Qi), which does not mutate the list, to common lisp and compared to the bubblesort in Bubblesort in Common Lisp, which does mutate the list. The result was that I found that (in Common Lisp) the version which mutated the list was significantly faster, for very large lists, than the version which did not mutate the list.
Expressions in Haskell are immutable. They cannot change after they are evaluated. Immutability makes refactoring super easy and code much easier to reason about. To “change” an object, most data structures provide methods taking the old object and creating a new copy.
There are no variables in Functional Programming. Stored values are still called variables because of history but they are constants, i.e. once x takes on a value, it's that value for life. Don't worry, x is usually a local variable so its life is usually short.
The ST
monad is exactly for the safe embedding of mutable operations within pure code. The type system is leveraged to ensure that none of the mutated data can escape the scope, thus you get the power of local mutable state without the peril of making your entire program stateful (which could destroy referential transparency or introduce race conditions).
Some documentation on the ST monad:
vsort
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With