concept sum in category kotlin

This is an excerpt from Manning's book The Joy of Kotlin.
Consider a list of integers. You could write a
sumfunction to compute the sum of the elements. Then you could write aproductfunction to compute the product of the elements or aminor amaxfunction to compute the minimum or the maximum of the list. Alternatively, you could also use thereducefunction for all these computations. This is abstraction. You abstract the part that’s common to all operations in thereducefunction, 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
![]()
Calls the sumfunction with the result oftailas its argumentAdds the result of headand the result ofsumThis function isn’t tail recursive, so you can’t use the
tailreckeyword, 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 tosumin 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) }