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?

More Than Five
  • 9,959
  • 21
  • 77
  • 127

3 Answers3

5

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.

Community
  • 1
  • 1
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
4

If course you can do complex recursion in Java. You could do complex recursion in assembler if you wanted to. But in Scala it is easier to do. 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.

Tesseract
  • 8,049
  • 2
  • 20
  • 37
2

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. So, the functional style just encourage you to write immutable code. That depends on yourself to choose whether to change the value or not.

lichenbo
  • 1,019
  • 11
  • 13