3

Ok, I get this all recursion is more functional because you are not changing the state of any object in an iteration. However there is nothing stopping you do this in scala.

  var magoo = 7; 

  def mergeSort(xs: List[Int]): List[Int] = {
    ...
    magoo = magoo + 1
    mergeSort(xs1, xs2);

  }

In fact, you can make recursion just as side effectless in Scala as you can in Java. So is it fair to say that Scala just make it easier to write concise recursion by using pattern matching? Like there is nothing stopping me writing any stateless recursion code in Java that I can write in Scala?

The point is really that in Scala complex recursion can be achieved with neater code. That's all. Correct?

4

3 回答 3

5

一些东西会阻止你用 Java 编写递归代码:尾调用消除 (TCE)。在 Java 中,可以在深度递归时获得 StackOverflowException,而在 Scala 中,调用将被优化(内部表示为循环)。

那么可以说 Scala 通过使用模式匹配更容易编写简洁的递归吗?

我认为在 Scala 中,这两个概念是相互正交的。

于 2013-05-18T13:36:43.437 回答
4

当然,您可以在 Java 中进行复杂的递归。如果你愿意,你可以在汇编器中进行复杂的递归。但在 Scala 中更容易做到。Scala 还具有尾调用优化,如果您想将任意迭代算法编写为递归方法而不会导致堆栈溢出或性能下降,这非常重要。

于 2013-05-18T13:37:19.987 回答
2

很少有编程语言实际上禁止您编写不可变代码。实际上,真正的纯函数式语言可能只是 Haskell,甚至 Scheme 和 ML 也有一些使用可变值的方法。所以,函数式风格只是鼓励你编写不可变的代码。这取决于您自己选择是否更改值。

于 2013-05-18T13:45:08.533 回答