/* * Extenstion function on List to reproduce the map method * Note need to use a name distinct from map, otherwise the already * defined map will always take precedence * @author gtowell * Created: Oct 25, 2021 */ fun List.mapgtM(fn: (T)->String): List { val ret = mutableListOf() fun irec(that:List) { if (that.count()==0) return; ret.add(fn(that.get(0))) return irec(that.drop(1)) } irec(this) return ret } fun List.mapgt(fn: (T)->String): List { fun irec(that:List, ret:List): List { if (that.count()==0) return ret; return irec(that.drop(1), ret+fn(that.get(0))) } return irec(this, emptyList()) } // for recursive function, you need to decalare the return type // even if you use the shorthand function definition in one expression // Doing it totally generically fun List.mapgt2(fn: (T)->U): List { fun irec(that:List, ret:List): List = if (that.count()==0) ret else irec(that.drop(1), ret+fn(that.get(0))) return irec(this, emptyList()) } fun main() { val aa = listOf(1,2,3,4) val rr = aa.mapgtM({ a:Int -> "<<%s %s>>".format(a, "A")}) println(rr) println(aa.mapgt({ a:Int -> "<<%s %s>>".format(a, "B")})) println(aa.mapgt2({ a:Int -> "<<%s %s>>".format(a, "C")})) }