纯功能语言中可能出现副作用的手段 [英] Possible means of side effectst in purely functional languages

查看:66
本文介绍了纯功能语言中可能出现副作用的手段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道功能语言中所有可能的副作用方式,甚至是理论上的,但实际上并未使用.

I would like to know all possible means of side effects in functional languages, even theoretical and not used in practice.

我了解Monads(Haskell)和唯一性类型(Clean).还有其他可能性吗?

I know about Monads (Haskell) and Uniqueness types (Clean). Are there any other possibilities?

推荐答案

水星默认情况下,所有内容都是纯净的(甚至是IO),并且如果不使用很少需要的功能就不可能编写不纯的代码.

In Mercury everything is pure by default (even IO), and it's impossible to to write impure code without using rarely needed features.

通过使用唯一性和最新状态参数,以类似于Clean(我相信)的方式处理Pure IO. Mercury认为唯一性是 mode 属性,而不是type属性. (在这种情况下,模式"或多或少是数据流的方向)

Pure IO is handled in a similar way to Clean (I believe), by using uniqueness and a state-of-the-world parameter. Mercury considers uniqueness to be a mode property rather than a type property though. (A "mode" in this context is more or less a data-flow direction)

但是水星还具有静态纯度系统.某些代码被编译器识别为不纯(调用外语接口或已知的不纯函数/谓词,访问可变变量,以及其他一些情况).此类代码必须显式声明为impure,否则它是编译器错误.由于编译器知道杂质,因此它不会执行可能影响不纯代码的重新排序或其他优化.如果可以在某种程度上围绕不纯运算提供纯接口,则可以向编译器保证函数/谓词实际上是纯函数.否则,所需的杂质声明会一直传播到main谓词.如果您准备好执行此操作,则可以使用Mercury进行必要的编程(尽管这样做并不有趣).

But Mercury also has a static purity system. Some code is recognised by the compiler as impure (calls to the foreign language interface, or to known impure functions/predicates, accessing mutable variables, and a few other cases). Such code must be explicitly declared impure or it is a compiler error. Since the compiler is aware of the impurity, it doesn't perform reorderings or other optimisations that could affect the impure code. If at some level you can provide a pure interface around the impure operations, you can promise to the compiler that a function/predicate is in fact pure. Otherwise the required impurity declarations propagate all the way up to the main predicate; if you're prepared to do this you could essentially program imperatively in Mercury (it wouldn't be fun though).

Mercury还具有 semipure 代码的概念.该代码不会对任何其他半纯或不纯代码的操作产生副作用(按定义,纯代码不受任何其他代码的副作用的影响),但可能受 的副作用的影响其他不纯代码.这些额外的信息意味着,不仅编译器可以看到"副作用,而且自身没有任何副作用,这些调用仍可以通过编译器自由地进行优化.如果不需要它们的结果,可以对其进行优化,只要不将它们移到impure调用上方,就可以对其进行重新排序.

Mercury also has a concept of semipure code. This is code that does not have a side effect the operation of any other semipure or impure code (pure code by definition is unaffected by side effects from any other code), but may be affected by side effects from other impure code. This extra level of information means that calls that are only not pure because they 'see' side effects but doesn't have any themselves can still be optimised much more freely by the compiler; they can be optimised away if their results are not needed, and they can be reordered so long as they aren't moved "over" an impure call.

这篇关于纯功能语言中可能出现副作用的手段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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