scala - 为什么不应该在函数式编程中使用变量赋值

标签 scala functional-programming

我正在学习函数式编程,我可以理解为什么不可变比可变对象更受欢迎。

This文章也解释的很好。

但我无法理解为什么要在纯函数内部执行赋值。

我能理解的一个原因是变量可变性导致锁定,因为在 scala 中的纯函数中,我们主要是尾递归,这会在调用堆栈而不是堆上创建变量/对象。

在函数式编程中应该避免变量赋值还有其他原因吗?

最佳答案

分配和重新分配之间存在差异。在函数式编程中不允许重新赋值,因为它的可变性在纯函数中是不允许的。允许变量赋值。

val a = 1 //assignment allowed

a = 2 //re-assignment not allowed

以不纯的方式(改变状态)从外部世界读取是函数式编程的副作用。

So, function accessing a global variable which can potentially be mutated is not pure.

让生活变得轻松。

一般

When you are disciplined life is less chaotic. Thats exactly what functional programming advocates. When life is less chaotic you can concentrate on better things in life.

所以,不变性的主要原因

It becomes hard to reason about the correctness of the program with mutations. In case of concurrent programs this is very painful to debug.

这意味着为了理解代码/程序或调试程序,很难跟踪变量所经历的变化。

突变是使程序难以理解和推理的副作用之一。

函数式编程强制执行此规则(使用不变性),以便代码可维护、可表达且易于理解。

变异是副作用之一

纯功能是没有副作用的。

副作用:

  1. 变量的变异
  2. 可变数据结构的变异
  3. 读取或写入文件/控制台(外部源)
  4. 向停止程序抛出异常

避免上述副作用使函数仅依赖于函数的参数,而不是任何外部值或状态。

Pure function is the most isolated function which neither reads from the world nor writes to the world. It does not halt or break the program control flow.

以上属性使纯函数易于理解和推理。

纯函数是数学函数

它是从 co-domain 到 range 的映射,其中 co-domain 中的每个值都映射到 range 中的一个值。

这意味着如果 f(2) 等于 4,那么无论世界的状态如何, f(2) 都是 4。

Pure function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output.

关于scala - 为什么不应该在函数式编程中使用变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42210171/

相关文章:

javascript - JavaScript 方法的部分应用 : how to retain th meaning of “this”

scala - 使用包含 self 类型的 Prop 创建 Actor

scala - Future中的 bool 逻辑[Boolean]

scala - Scala 中动态深度的 For 理解

functional-programming - 这个函数有标准名称吗?

functional-programming - monad 除了提高可读性和生产力之外还有其他作用吗?

scala - Actor 的 Spark 流

serialization - 您可以覆盖 scala @serializable 对象中的流编写器吗?

scala - 在 Scala 中实现 ifTrue、ifFalse、ifSome、ifNone 等以避免 if(...) 和简单的模式匹配

functional-programming - 我应该在 OCaml 的 List 上实现 PriorityQueue (Heap) 吗?