Haskell中的纯函数是否有可能突变变量的本地副本? [英] Is it possible for pure functions in Haskell to mutate local copies of variables?
问题描述
Haskell中的纯函数可能会使变量的本地副本发生变化,如clojure可以在?
在看起来纯粹的调用者但内部使用突变的功能和一般的共识似乎只要对变量的局部拷贝进行突变(即突变的效果不逃避功能并且具有非局部效应),纯函数就可以执行突变。
当我翻译沉思中的气泡排序时出现了问题(本地突变,全局突变,可变数据结构,气泡中的气泡),其不将列表更改为常用lisp,并与常用Lisp中的Bubblesort 中的bubblesort进行比较 ,其确实更改列表。结果是,我发现(在Common Lisp中)对于非常大的列表而言,改变列表的版本比没有改变列表的版本明显更快。
有关ST monad的一些文档:
- 黑洞
- Haskell Wiki
- ST快速排序向量(堆栈溢出) - 请参见
vsort
。 - 原文
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.
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
这篇关于Haskell中的纯函数是否有可能突变变量的本地副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!