简体   繁体   English

Scala递归没有副作用

[英]Scala recursion no side effects

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. 然而,没有什么能阻止你在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. 事实上,你可以像在Java中一样在Scala中进行递归。 So is it fair to say that Scala just make it easier to write concise recursion by using pattern matching? 那么可以公平地说Scala只是通过使用模式匹配来简化编写简洁的递归吗? Like there is nothing stopping me writing any stateless recursion code in Java that I can write in Scala? 就像没有什么能阻止我在Java中编写任何我可以在Scala中编写的无状态递归代码?

The point is really that in Scala complex recursion can be achieved with neater code. 关键在于Scala复杂的递归可以用更简洁的代码实现。 That's all. 就这样。 Correct? 正确?

There is something that will stop you from writing recursion code in Java: Tail call elimination (TCE). 有些东西会阻止你在Java中编写递归代码:尾部调用消除(TCE)。 In Java it is possible to get StackOverflowException on deep recursion, whereas in Scala tail calls will be optimized (internally represented as loops). 在Java中,可以在深度递归时获得StackOverflowException,而在Scala中, 尾部调用将被优化 (内部表示为循环)。

So is it fair to say that Scala just make it easier to write concise recursion by using pattern matching? 那么可以公平地说Scala只是通过使用模式匹配来简化编写简洁的递归吗?

I think in Scala those two concepts are orthogonal to each other. 我认为在Scala中这两个概念是相互正交的。

If course you can do complex recursion in Java. 如果当然可以在Java中进行复杂的递归。 You could do complex recursion in assembler if you wanted to. 如果你愿意,你可以在汇编程序中进行复杂的递归。 But in Scala it is easier to do. 但在Scala中,这样做更容易。 Also Scala has tail call optimisation which is very important if you want to write any arbitrary iterative algorithm as a recursive method without getting a stack overflow or performance drop. 此外,Scala还具有尾调用优化功能,如果您希望将任意迭代算法编写为递归方法而不会导致堆栈溢出或性能下降,则非常重要。

Few programming language actually forbids you writing immutable code. 很少有编程语言实际上禁止你编写不可变代码。 Actually, the real pure functional language might be just Haskell, and even Scheme and ML have some way to use mutable value. 实际上,真正的纯函数式语言可能只是Haskell,甚至Scheme和ML都有一些方法可以使用可变值。 So, the functional style just encourage you to write immutable code. 因此,功能样式只是鼓励您编写不可变代码。 That depends on yourself to choose whether to change the value or not. 这取决于你自己选择是否改变价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM