/* * Another tail recursive function. This one sums this items * in a list of integers. Note, doing this generically over * all number types (and only number types) is a pain. Easiest * (imo) way is to overload and write independent function for * each type * * In addition to just doing this TR, we see: * 1. Kotlin allows default values for function parameters * 2. Given default values, kotlin allows named parameters in function call * 3. The "elvis" operator. "?". This allows the parameter to * be null. It also REQUIRES that null be explicitly handled * This pairling allows Kotlin to be "null safe" * * @author ggtowell * Created: Aug 2, 2021 */ fun main() { // call with one positional parameter println(bb(listOf(1,2,3,4,5))) // call with one positional, but it is null println(bb(null)) // call with no params println(bb()) // call with named param println(bb(b3=listOf(2,3,4,5,6))) // call with other named param println(bb(bsum=5)) } /* * Recursive function to compute the sum of a list of integers * Each param has default values so can do anything from all * positional notation to named to nothing * @param b3 -- a list of integers : default=null * @param bsum -- the number to consider to be the sum of an empty or null list: default 0 */ tailrec fun bb(b3: List, bsum:Int = 0):Int { //if (b3==null) return bsum if (b3.isEmpty()) return bsum return bb(b3.drop(1), bsum+b3.first()) }