Skip to content

Instantly share code, notes, and snippets.

@ramirez7
Last active July 19, 2021 20:21
Show Gist options
  • Select an option

  • Save ramirez7/398157c8a37452549c15da03de3d0cdb to your computer and use it in GitHub Desktop.

Select an option

Save ramirez7/398157c8a37452549c15da03de3d0cdb to your computer and use it in GitHub Desktop.
// Kotlin implementation of `fix`
// https://hackage.haskell.org/package/base-4.15.0.0/docs/Data-Function.html#v:fix
//
// Note the use of `Lazy`. It is the key to this working at all - without it, we
// spin until we get a stack overflow.
fun <A> fix(f: (Lazy<A>) -> A): A =
object {
val x: A by lazy {
f(lazy { this.x })
}
}.x
fun main(args: Array<String>) {
// Port of the `fix`-based factorial from the above haddocks
//
// >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5
// 120
val fac = fix<(Int) -> Int> { rec -> { n -> if (n <= 1) 1 else n * rec.value(n - 1) } }
println(fac(5))
}
@ramirez7
Copy link
Author

repl.it says it works 💯

> kotlinc -d main.jar main.kt
> kotlin -classpath main.jar MainKt
120

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment