Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for pure functions in Haskell to mutate local copies of variables?

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.

like image 320
artella Avatar asked Oct 13 '13 12:10

artella


People also ask

Are variables immutable in Haskell?

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.

Do functional languages have variables?

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.


1 Answers

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:

  • Haddock
  • Haskell Wiki
  • ST to quick sort vectors (stack overflow) - see the function named vsort.
  • The original paper
like image 181
Thomas M. DuBuisson Avatar answered Sep 27 '22 22:09

Thomas M. DuBuisson