// == Design Pattern == // Another layer of abstraction :) // - A general, reusable solution to a commonly // occurring problem in software design // - These are usually not concrete code to // copy-paste, but rather a template/description // of how to solve a problem // - These formalize best practices and can simplify // communication with other developers (i.e., can // speak first at the level of design patterns, // before diving down into functions/classes) // // == Accumulator == // Updates a result during some sort of // iterative process (e.g., loop) // General form... // 1. Initialize a variable (the accumulator) // 2. Execute a repetitive proces // (e.g., loop over a set of data, a range, // or until a condition is satisfied) // 3. Update the variable during each repetition // 4. After the process is complete, // the variable has a useful result // Imperative/loopy... // fun loopyAccumulator() { // var acc = initialVal // for/while/do { // // update acc // } // return acc // } // re-implement the list constructor! fun buildListImp(n: Int, f: (Int)->T): List { var myResult = mutableListOf() for (i in 0 until n) { myResult.add(f(i)) } return myResult } println(buildListImp(5) { it + 1 }) println(buildListImp(5) { outer -> buildListImp(outer + 1) { inner -> buildListImp(inner+1, { "£" }).joinToString("") } }) // Functional... // 1. Use a local, recursive function // to implement the iteration // (with an accumulator argument) // 2. Recursive call includes the // change to the accumulator // 3. Initialize via a call to the // local function // fun recursiveAccumulator() { // fun helpAccumulate( // acc: AccType, // iterationVar: Thing // ): AccType { // return when (doneCondition) { // true -> acc // false -> helpAccumulate( // addTo(acc), // makeSmaller(iterationVar) // ) // } // } // return helpAccumulate( // initialAccVal, // startingIterationVal // ) // } fun buildListFunc(n: Int, f: (Int)->T): List { // helper that builds the list // while counting down n downTo 0 // accumulator: list so far fun helpBuild(accumulator: List, i: Int): List { return when (i == 0) { true -> accumulator false -> helpBuild( accumulator + listOf(f(n-i)), i - 1 ) } } return helpBuild( emptyList(), n ) } println(buildListFunc(5) { it + 1 }) println(buildListFunc(5) { outer -> buildListFunc(outer + 1) { inner -> buildListFunc(inner+1, { "£" }).joinToString("") } })