如果它从外部读取一些数据而不是参数,它是一个纯函数吗? [英] Is it a pure function if it reads some data from outside rather than parameters?
问题描述
在Scala函数式编程一书中,它提供了一些关于副作用的例子,如: 我的问题是,从外部读取一些数据比参数使得函数不纯吗? Eg 编辑:按照此答案: https://stackoverflow.com/a/31377452/342235 ,我的功能实际上不是功能,它是一种方法,所以我给一个函数版本,并询问相同的问题: 数据不是不纯;该函数每次仍会返回相同的值。如果 (当然,也可以通过反射来改变 值得注意的是你的函数不是纯粹的,因为 In the book of "functional programming in Scala", it gives some examples about side-effects, like: My question is, is reading some data from outside rathen than the parameters makes the function impure? E.g. Is the Edit: as per this answer: https://stackoverflow.com/a/31377452/342235, my "function" is not actually function, it's a method, so I give a function version of it, and ask the same question:
Reading from immutable data is not impure; the function will still return the same value every time. If (Of course it might be possible to e.g. alter It's worth noting that your function is not pure because 这篇关于如果它从外部读取一些数据而不是参数,它是一个纯函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
val name =Scala
def upcase()= name.toUpperCase
val name =Scala
val upcase:()=> String =()=> name.toUpperCase
name
是 var
,那么这个函数将是不纯的,因为外部的东西可能会改变名称
,因此对 upcase()
的多次调用可能会计算出不同的值。
name
。我们只能谈论关于什么样的函数可以调用给定函数的一些概念的纯度,以及我们认为什么样的副作用是等价的)
toUpperCase
不纯;它取决于系统的默认语言环境,并且可能在不同的系统上产生不同的结果(例如在土耳其语系统上,i.toUpperCase ==İ
)。你应该总是传递一个明确的 Locale
,例如 def upcase()= name.toUpperCase(Locale.ENGLISH)
;那么该函数将是纯粹的。
val name = "Scala"
def upcase() = name.toUpperCase
upcase
function pure or not?
val name = "Scala"
val upcase: () => String = () => name.toUpperCase
name
were a var
then that function would be impure, since something external could change name
, so multiple calls to upcase()
might evaluate to different values.name
through reflection. Properly we can only talk about purity with respect to some notion of what kind of functions are allowed to call a given function, and what kind of side effects we consider to be equivalent)toUpperCase
is not pure; it depends on the system's default Locale, and may produce different results on different systems (e.g. on a Turkish system, "i".toUpperCase == "İ"
). You should always pass an explicit Locale
, e.g. def upcase() = name.toUpperCase(Locale.ENGLISH)
; then the function will be pure.