Created
July 14, 2014 14:01
-
-
Save milessabin/71ea435a2f2ec8a381c1 to your computer and use it in GitHub Desktop.
fixpoint combinator in Scala using shapeless's Lazy (it could be done similarly with Scalaz's Need).
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
| scala> import shapeless._ | |
| import shapeless._ | |
| scala> def fix[A](f: Lazy[A] => Lazy[A]): Lazy[A] = f(Lazy(fix(f).value)) | |
| fix: [A](f: shapeless.Lazy[A] => shapeless.Lazy[A])shapeless.Lazy[A] | |
| scala> val step = (rec: Lazy[Int => Int]) => Lazy((n: Int) => if(n == 0) 1 else n*rec.value(n-1)) | |
| step: shapeless.Lazy[Int => Int] => shapeless.Lazy[Int => Int] = <function1> | |
| scala> val fact = fix(step).value | |
| fact: Int => Int = <function1> | |
| scala> fact(5) | |
| res0: Int = 120 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment