在我看来,功能纯净的力量在于深层代码路径可以被验证为无副作用时。人们在纯说明符内部的代码树规模方面有什么经验,代码重用级别如何?
我发现了几件事:std.algorithm
大多没有标记为pure
,但是可能是纯净的,要么是纯格式的算法要求实例化函数或mixin的纯净,要么是纯度说明符本身是静态多态的。
像to!string( someInt )
这样的有用转换器目前还不是纯净的。
用户定义的结构似乎存在以下问题(如下所示):
1.嵌套结构上的纯析构函数
2.即使在非嵌套结构上,也具有纯postblit函数
以下代码当前在DMD 2.052 Win 32位上给出多个错误
struct InnerStruct
{
pure this(this) {}
pure ~this() {}
}
struct OuterStruct
{
InnerStruct innerStruct;
pure this(this) {}
pure ~this() {}
}
pure void somePureFunc()
{
OuterStruct s1 = OuterStruct(); // pure nested destructor does not compile
OuterStruct s2 = s1;
InnerStruct is1 = InnerStruct(); // pure non-nested destructor seems to compile
InnerStruct is2 = is1; // pure non-nested postblit does not compile
}
void main()
{
somePureFunc();
}
pure_postblit.d(18): Error: pure function 'somePureFunc' cannot call impure function '__cpctor'
pure_postblit.d(20): Error: pure function 'somePureFunc' cannot call impure function '__cpctor'
pure_postblit.d(18): Error: pure function 'somePureFunc' cannot call impure function '~this'
pure_postblit.d(17): Error: pure function 'somePureFunc' cannot call impure function '~this'
最佳答案
从理论上讲,D中的pure
的意义在于,无论该函数如何实现,它都应保证没有副作用。 D中有两种纯度:
pure
的所有函数都是纯函数。他们可能无法访问任何全局可变状态(全局变量,线程局部变量,static
变量等)或执行I / O。但是,他们可能会改变自己的观点。这些函数的要点是可以从强纯函数(在下面详细介绍)中调用它们,而不会违反强纯函数的保证。 const
和immutable
类型的构造函数可以用来保证这一点。 (在处理结构和类时,this
指针被视为一个参数。)强纯函数具有函数编程人员所谈论的所有不错的属性,即使它们是使用可变状态实现的也是如此。对于任何给定的参数,纯函数都始终返回相同的值,并且没有明显的副作用。高度纯函数是引用透明的,这意味着它们的返回值可以用给定的一组参数替换对它们的调用,而不会影响可观察的行为。任何强纯函数都可以与任何其他强纯函数并行安全地执行。 不幸的是,通用代码和
pure
(以及const
和immutable
)之间的交互作用很差。已经有一些解决此问题的建议,但尚未被接受。\ std.algorithm被编写为尽可能通用,因此它不能要求其lambda函数及其接受的范围是纯净的。此外,在D2中添加的类型系统功能通常是该语言中最容易出错的功能,因为在解决相关问题之前已优先考虑了更基本的内容。目前,除了诸如std.math之类的琐碎情况外,
pure
基本上不可用。
关于functional-programming - D中的纯函数式编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5812186/