问题描述
假设我有以下两个F#函数:
Suppose I have these two F# functions:
let sq x = x*x
let tm = DateTime.Now
很明显,sq是纯净的,因为它总是为给定的输入返回相同的值,而tm是不纯的,因为每次调用它都会返回不同的值.
Clearly sq is pure in that it will always return the same value for a given input while tm is impure because it will return a different value each time it is called.
通常,有一种方法可以确定F#中的某个特定函数是纯函数还是不纯函数,而无需分析其功能,换句话说就是逐行读取它?
In general is there a way to determine if a particular function in F# is pure or impure without analyzing what it does, in other words reading it line by line?
或者,有一种方法可以给函数添加注释,以告诉编译器在编写函数时该函数是纯函数还是不纯函数?
Alternatively is there a way to annotate a function to tell the compiler that the function is pure or impure when you write it?
最后,当调用属于公共语言运行时(例如DateTime)的一部分的函数时,如何不进行尝试就知道它是纯净的还是不纯净的?
Finally when calling a function that is part of the common language runtime (such as DateTime) how can one tell if it is pure or impure without trying it?
注意:纯"是指Wikipedia的定义: http://en.wikipedia. org/wiki/Pure_function (固定链接)
Note: by "pure" I mean the definition from Wikipedia: http://en.wikipedia.org/wiki/Pure_function (permalink)
-
在给定相同参数的情况下,该函数始终求值相同的结果值 值.函数结果值不能依赖于任何 隐藏的信息或状态可能随着程序执行而改变 继续执行或在程序的不同执行之间进行,也不可以 取决于I/O设备的任何外部输入.
The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices.
结果评估不会引起任何语义上可观察的方面 效果或输出,例如可变对象的突变 或输出到I/O设备.
Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.
推荐答案
F#不提供任何功能和工具来检查方法是否纯净,因此一个简单的答案是您必须自己检查此属性.
F# does not provide any features and tools for checking that methods are pure, so a simple answer is that you have to check this property yourself.
在F#之外,值得注意的是代码合同库有一个纯方法的概念(可以用进行标记PureAttribute
),但我不完全确定那里的检查故事是什么.我认为代码合同附带了用于分析IL的静态检查器(并且也应该适用于F#),但这是一项非常艰巨的任务,因此我希望它会受到很大的限制.但是,PureAttribute
用于某些BCL方法,因此您可以判断出某些标准.NET方法是纯净的.
Outside of F#, it is worth noting that Code Contracts library has a notion of pure methods (and they can be marked with PureAttribute
), but I'm not entirely sure what is the checking story there. I think Code Contracts come with static checker that analyses IL (and should work for F# too), but this is quite difficult task, so I would expect it to be quite limited. However, the PureAttribute
is used on some BCL methods, so you can tell that some standard .NET methods are pure.
这篇关于如何判断F#函数是否纯净?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!