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

五迷三道 提交于 2019-12-10 13:38:59

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/19345489/is-it-possible-for-pure-functions-in-haskell-to-mutate-local-copies-of-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!