Last active
March 4, 2020 03:43
-
-
Save jubinjacob19/99989899ddb2d8e1d1055730e6ecace4 to your computer and use it in GitHub Desktop.
The Y combinator in Kotlin. A single argument Y combinator is used to find the factorial of a number.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main(args: Array<String>) { | |
if (args.count() == 0) { | |
println("Please input a number") | |
} else { | |
try { | |
val n = args[0].toInt() | |
val factorial = y<Int,Int> {f-> { n-> | |
if (n == 0) 1 | |
else n * f(n - 1) | |
} } | |
val fact = factorial(n) | |
println("Factorial of $n is $fact") | |
} catch(e: NumberFormatException) { | |
println("Please input a number") | |
} | |
} | |
} | |
fun <In, Out> y(f: (_:(n: In) -> Out)->(n: In) -> Out) : (n: In) -> Out { | |
return { | |
f(y(f))(it) | |
} | |
} |
In my opinion, it is more understandable this way: fun <In, Out> y(f: (_: (n: In) -> Out) -> (n: In) -> Out): (n: In) -> Out = { p -> f(y(f))(p) }
, but still great
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is simply lovely. Thank you. ❤️