Skip to content

Instantly share code, notes, and snippets.

@jubinjacob19
Last active March 4, 2020 03:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jubinjacob19/99989899ddb2d8e1d1055730e6ecace4 to your computer and use it in GitHub Desktop.
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.
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)
}
}
@tpreviero
Copy link

This is simply lovely. Thank you. ❤️

@downloadpizza
Copy link

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