Haskell中的纯函数是否有可能突变变量的本地副本? [英] Is it possible for pure functions in Haskell to mutate local copies of variables?

查看:146
本文介绍了Haskell中的纯函数是否有可能突变变量的本地副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell中的纯函数可能会使变量的本地副本发生变化,如clojure可以在



看起来纯粹的调用者但内部使用突变的功能和一般的共识似乎只要对变量的局部拷贝进行突变(即突变的效果不逃避功能并且具有非局部效应),纯函数就可以执行突变。



当我翻译沉思中的气泡排序时出现了问题(本地突变,全局突变,可变数据结构气泡中的气泡),其将列表更改为常用lisp,并与常用Lisp中的Bubblesort 中的bubblesort进行比较 ,其确实更改列表。结果是,我发现(在Common Lisp中)对于非常大的列表而言,改变列表的版本比没有改变列表的版本明显更快。

ST monad是用于在纯代码中安全嵌入可变操作的。利用类型系统来确保没有任何变异的数据可以逃避范围,因此你获得局部可变状态的力量,而不会使你的整个程序有状态(这可能破坏引用透明度或引入竞争条件)的危险。 p>

有关ST monad的一些文档:




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:

这篇关于Haskell中的纯函数是否有可能突变变量的本地副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆