tail recursion

  • One of the fundamental tools of the functional programmer toolbox is the concept of recursion. It can be defined briefly as calling a function from inside itself. Recursive functions exist in many languages, even outside the domain of FP. To name one of the oldest, the C language allows recursive calls. Recursive functions are a cleaner and more elegant way to express problems without using loops. The only caveat is never forget to check for a termination condition to avoid endless looping. Let's see how the factorial of a number can be calculated in Scala with a naif recursive call:

    scala> def f(x: Int): Int = if (x == 1) 1 else x * f(x - 1)
    f: (x: Int)Int

    scala> f(2)
    res0: Int = 2

    scala> f(3)
    res1: Int = 6

    scala> f(4)
    res2: Int = 24

  The Cog In The Machine On Which All Depends