Skip to content

Instantly share code, notes, and snippets.

@KucherenkoIhor
Created February 8, 2018 05:55
Show Gist options
  • Save KucherenkoIhor/5d6ee5d350c8275cd4b7fec3d9fa0028 to your computer and use it in GitHub Desktop.
Save KucherenkoIhor/5d6ee5d350c8275cd4b7fec3d9fa0028 to your computer and use it in GitHub Desktop.
KotlinFunctionComposition
val xMinus3 = {x: Int -> x - 3}
val composedFull = compose(::xPlusX, ::add5To, ::xMulX)
val composed4 = compose(xMinus3, ::xPlusX, ::add5To, ::xMulX)
fun <R> compose(vararg funs: (R) -> R): (R) -> R = { x: R ->
funs.reduceRight { acc, function -> { acc(function(it)) } }(x)
}
fun xPlusX(x: Int) = x + x
fun add5To(x: Int) = x + 5
fun xMulX(x: Int) = x * x
fun main(vars: Array<String>) {
println(composedFull(6))
println(composed4(6))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment