concept sum in category kotlin

appears as: sum, sum, sums
The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

Consider a list of integers. You could write a sum function to compute the sum of the elements. Then you could write a product function to compute the product of the elements or a min or a max function to compute the minimum or the maximum of the list. Alternatively, you could also use the reduce function for all these computations. This is abstraction. You abstract the part that’s common to all operations in the reduce function, and you pass the variable part (the operation) as an argument.

The distinction between recursion and corecursion is illustrated in figures 4.3 and 4.4. These figures represent the computation of the sum of a list of integers. Addition is a bit special because

Figure 4.5 A flow chart of the imperative computation of the sum of n first integers

Fig04_05.png
  • Calls the sum function with the result of tail as its argument
  • Adds the result of head and the result of sum
  • This function isn’t tail recursive, so you can’t use the tailrec keyword, and you won’t be able to use this function with lists of more than a few thousand elements. But you can rewrite this function in order to put the call to sum in the tail position:

    fun sum(list: List<Int>): Int {
        tailrec fun sumTail(list: List<Int>, acc: Int): Int =
                if (list.isEmpty())
                    acc
                else
                    sumTail(list.tail(), acc + list.head())
        return sumTail(list, 0)
    }

    Here, the sumTail helper function is tail recursive and can be optimized through TCE. As this helper function will never be used elsewhere, the best place to put it is inside the sum function.