/** * A ridiculously complex example of tail recursion in Kotlin * This goes deep into function programming in addition to doing * simple tail recursion *@author gtowell * Created Aug 2021 */ import java.time.LocalDateTime import java.time.Duration @Suppress("UNUSED_PARAMETER") fun main(args: Array) { looper(3); } // Do everything idx times fun looper(idx: Int) { if (idx<0) { return; } println("NOT TR") // the thing in {} is an anonymous function that is passed to the timer function timer( { println(sum(10000)) } ); println("TR") timer( { println(sumTR(10000)) } ); looper(idx-1); } //When passing / returning functions as arguements, I like to define types // This one is weird as functional programing goes, because it does // not return value!! typealias WKLambda = ()->Unit; /* * Time how long the passed in function takes to complete. * @param funcc -- the function to be timed * @return the time required to complete the passed in function. */ fun timer (funcc: WKLambda) : Duration { val nw = LocalDateTime.now() funcc() val dur = Duration.between(nw, LocalDateTime.now()) println("The operation took ${dur} ms") return dur } // add up numbers from 1 to N // Not tagged as tail recursive fun sum(max:Long, sss:Long=0) : Long { if (max<=0) return sss; return sum(max-1, sss+max); } // add up numbers from 1 to N // Tagged as tail recursive // Otherwise identical to summ tailrec fun sumTR(max:Long, sss:Long=0) : Long { if (max<=0) return sss; return sumTR(max-1, sss+max); }