Skip to content

Instantly share code, notes, and snippets.

@enshahar
Last active June 19, 2020 11:55
Show Gist options
  • Save enshahar/296b3665c39d67c8539c3957205f81c0 to your computer and use it in GitHub Desktop.
Save enshahar/296b3665c39d67c8539c3957205f81c0 to your computer and use it in GitHub Desktop.
Comparing fold and reduce
class FoldAndReduce {
val appendSC = { s: String, c: Char -> s + c }
val appendCS = { c: Char, s: String -> c + s }
val add = { x: Int, y: Int -> x + y }
val sub = { x: Int, y: Int -> x + y }
val cons = { x: Int, y: List<Int> -> listOf(x, *y.toTypedArray()) }
val appendList = { y: List<Int>, x: Int -> y + x }
val list1 = listOf(1, 2, 3, 4, 5)
val list1rev = list1.reversed()
val string = "Fold And Reduce"
fun main(args:Array<String>) {
println("[1,2,3,4,5].reduce(+) = ${list1.reduce(add)}")
println("[1,2,3,4,5].reduce(-) = ${list1.reduce(sub)}")
println("[1,2,3,4,5].fold(0)(+) = ${list1.fold(0, add)}")
println("[1,2,3,4,5].foldr(0)(+) = ${list1.foldRight(0, add)}")
println("[1,2,3,4,5].fold(0)(-) = ${list1.fold(0, sub)}")
println("[1,2,3,4,5].foldr(0)(-) = ${list1.foldRight(0, sub)}")
println("")
println("[1,2,3,4,5].reversed().reduce(+) = ${list1rev.reduce(add)}")
println("[1,2,3,4,5].reversed().reduce(-) = ${list1rev.reduce(sub)}")
println("[1,2,3,4,5].reversed().fold(0)(+) = ${list1rev.fold(0, add)}")
println("[1,2,3,4,5].reversed().foldr(0)(+) = ${list1rev.foldRight(0, add)}")
println("[1,2,3,4,5].reversed().fold(0)(-) = ${list1rev.fold(0, sub)}")
println("[1,2,3,4,5].reversed().foldr(0)(-) = ${list1rev.foldRight(0, sub)}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment