// == Process of Abstraction == // 1. Write something twice -> :: spidey sense!! :: // 2. Compare, differences -> parameters // 3. Create abstraction // 4. Re-write #1 as special cases fun sortNumsByOp(nums: List, compareNumberOp: (Int, Int)->Boolean): List { fun insert(sortedList: List, num: Int): List { return when (sortedList.isEmpty()) { true -> listOf(num) false -> when (compareNumberOp(num, sortedList[0])) { true -> listOf(num) + sortedList false -> sortedList.take(1) + insert(sortedList.drop(1), num) } } } return nums.fold(emptyList(), ::insert) } fun sortIncreasing(nums: List): List { return sortNumsByOp(nums, ::lteNums) } fun sortDecreasing(nums: List): List { return sortNumsByOp(nums, ::gteNums) } // fun sortIncreasing(nums: List): List { // fun insert(sortedList: List, num: Int): List { // return when (sortedList.isEmpty()) { // true -> listOf(num) // false -> when (lteNums(num, sortedList[0])) { // true -> listOf(num) + sortedList // false -> sortedList.take(1) + insert(sortedList.drop(1), num) // } // } // } // return nums.fold(emptyList(), ::insert) // } // fun sortDecreasing(nums: List): List { // fun insert(sortedList: List, num: Int): List { // return when (sortedList.isEmpty()) { // true -> listOf(num) // false -> when (gteNums(num, sortedList[0])) { // true -> listOf(num) + sortedList // false -> sortedList.take(1) + insert(sortedList.drop(1), num) // } // } // } // return nums.fold(emptyList(), ::insert) // } // is the first less than or equal to the second? fun lteNums(num1: Int, num2: Int): Boolean { return num1 <= num2 } // is the first greater than or equal to the second? fun gteNums(num1: Int, num2: Int): Boolean { return num1 >= num2 } val exNums = listOf(9, 2, 5) println(sortIncreasing(exNums)) println(sortDecreasing(exNums))