functions

  • In Scala a function is an object. This can be deduced from the existence of a set of traits called scala.Function, scala.Function1,... scala.Function22. The traits define the abstract method apply() (I've already written something about it) and some concrete methods. The use of this trait is like this:

    object Main extends App {
       val succ = (x: Int) => x + 1
       val anonfun1 = new Function1[Int, Int] {
         def apply(x: Int): Int = x + 1
       }
       assert(succ(0) == anonfun1(0))
    }

    This example is taken Scala documentation. What can a function like anonfun1 be useful for? Well, the code shows by itself: succ(0) is equal to anonfun(0). The code of succ and anonfun1 is the same: it takes an Int argument and return an Int which is the argument plus one.

  • 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