为什么每次我尝试更改 Scala 中任何数据结构的值时都没有任何反应?

Ana*_*sia 0 arrays syntax functional-programming scala immutability

当我使用会更改数组或列表的东西时,通常会发生这种情况。例如这里:nums.drop(i)。我尝试调试,但它甚至看不到该行,如果您向我解释这种行为,我将不胜感激

    def findDuplicates(nums: Array[Int]): List[Int] = {
    nums.foldLeft(0)((accumValue, nextEl) => {
      if (nums.tail.contains(nextEl)) {
        accumValue
      } else {
        nums.drop(accumValue)
        accumValue
      }
    })

    nums.toList
  }
Run Code Online (Sandbox Code Playgroud)

Dmy*_*tin 6

该方法drop不会将元素放置到位。它返回一个新数组,其中不包含删除的元素。并且您不以任何方式使用这个新数组(您不将此值分配给某些val等),您只是忽略结果。

Scala 是面向表达式的。块的值(块返回的值)是块中的最后一个表达式。所以区块的价值

{
  nums.drop(accumValue)
  accumValue
}
Run Code Online (Sandbox Code Playgroud)

accumValue

该方法的签名是

/** The rest of the array without its `n` first elements. */
def drop(n: Int): Array[A] = ...
Run Code Online (Sandbox Code Playgroud)

https://github.com/scala/scala/blob/v2.13.10/src/library/scala/collection/ArrayOps.scala#L374

它不是def drop(n: Int): Unit

如果调试器看不到该行,则编译器可能会看到您没有使用结果,并且编译器只是排除该行。

您应该习惯函数式编程,在函数式编程中,您不会就地改变事物(这将是副作用),而是获取一些值,对其进行转换并返回结果。您已经开始使用foldLeft和 累加器,这是 FP 的典型情况。

函数式编程和非函数式编程

过程式编程和函数式编程有什么区别?