/* * The map and fold function and lambda * map returns a new list where the items in the original list have been * transformed by the lambda * fold returms a single thing that results from combining the list * according to the lambda * There are other functions like map and fold * @author ggtowell * @created Aug 3, 2021 */ fun main() { val aa = listOf(1,2,3,4,5,6,7,8,9) println(aa) // create an anonymous function to square items val f2 = fun(av:Int):Int { return av*av} val f2l = { av:Int -> av*av*av } // use map with the anonyous func println(aa.map(f2)) println(aa.map(f2l)) // map with lambda to double items val aa2 = aa.map({av -> av*2 }) println(aa2) // map with labmda to turn items into strings with [] val aaS = aa.map({aq -> String.format("<<%d>>", aq)}) println(aaS) // map to turn list into list of lists println("AAA" + aa.map({aq -> listOf(aq*aq)})) // fold to compute sum // the arguement in parens is the initial value println(aa.fold(0){sum, vl -> sum+vl}) // fold to build a string representation println(aa.fold("aa"){sum, vl -> String.format("%s %d ", sum, vl)}) }