1

Two functions:

def eat(): Unit = sleep()
def sleep(): Unit = eat()

Both of them are recursive functions, because they called themselves in the body (indirectly), right?

But are they tail recursive functions?

Freewind
  • 193,756
  • 157
  • 432
  • 708

1 Answers1

6

Both of them are recursive functions, because they called themselves in the body (indirectly), right?

Yes, this is called mutual recursion.

But are they tail recursive functions?

Yes, they are, as the call is the return value of the body. However, afaik the Scala compiler does not optimise these into while loops, it only does so for self-recursive functions. See Does Scala support tail recursion optimization? for details, and How to use TailCalls? for a workaround.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 2
    To be precise: Scala only optimizes *direct tail-recursion*, when a method *directly* calls *itself* in *tail position*. This is a somewhat unfortunate consequence of wanting to stay interoperable with the host language, because the JVM's `GOTO` only allows you to jump to a target inside the same method. Note that in an object-oriented language it isn't actually immediately obvious whether or not a method calls "itself", because it might, for example, call a different overload or an overridden version. – Jörg W Mittag Jul 22 '15 at 22:15