/* * Yet another version of summing a list * This one, instead of gettign the head and recurring on * the rest of the list, does everything positionally. Depending * on the implementation of the list, this version may be much * faster, or must slower, than the other version */ // I like defining types for functions. typealias LSum = (Int)->Int; fun main() { // get back a function val f = bb(mutableListOf(1,2,3,4,5,6)) // need to ensure that the returned funxtion is not null if (f!=null) { // execute function println(f(0)) println(f(10)) } } /* * Another list summer -- this returns a closure, * so that the summing so not actually done until the returned * function is called. * This could have issues in a multi-threaded environment because of the * b3 parameter. Problem is that anonymous functions cannot have optional * parameters * @param bb3 -- a list of integers : default=null */ fun bb(bb3: List?=null) : LSum? { if (bb3==null) return null val b3 = bb3.toMutableList() // define an "anonymous function". So called because there // is no name after the fun keyword. // NOTE lateinit -- needed for recursive anonymous function lateinit var funcc : LSum funcc = fun (s4:Int) : Int { if (b3.isEmpty()) { b3.addAll(bb3) return s4 } val tmp = b3.first() b3.removeFirst() return funcc(s4+tmp) } return funcc }