Last active
July 19, 2021 20:21
-
-
Save ramirez7/398157c8a37452549c15da03de3d0cdb to your computer and use it in GitHub Desktop.
fix in Kotlin https://replit.com/@ramirez7/fixkt#main.kt
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
| // 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)) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
repl.it says it works 💯