Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  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?

like image 413
More Than Five Avatar asked Dec 07 '25 10:12

More Than Five


1 Answers

There is something that will stop you from writing recursion code in Java: Tail call elimination (TCE). In Java it is possible to get StackOverflowException on deep recursion, whereas in Scala tail calls will be optimized (internally represented as loops).

So is it fair to say that Scala just make it easier to write concise recursion by using pattern matching?

I think in Scala those two concepts are orthogonal to each other.

like image 69
om-nom-nom Avatar answered Dec 10 '25 02:12

om-nom-nom