Skip to content

Instantly share code, notes, and snippets.

@milessabin
Created July 14, 2014 14:01
Show Gist options
  • Select an option

  • Save milessabin/71ea435a2f2ec8a381c1 to your computer and use it in GitHub Desktop.

Select an option

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).
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