Skip to content

Instantly share code, notes, and snippets.

@aboisvert
Created August 2, 2010 05:21
Show Gist options
  • Save aboisvert/504144 to your computer and use it in GitHub Desktop.
Save aboisvert/504144 to your computer and use it in GitHub Desktop.
/** Fixed point combinator: The essence of recursion */
def fix[T, R](f: (T => R) => (T => R)): (T => R) = new Function1[T, R] {
def apply(t: T): R = f(this)(t)
}
/** Factorial definition with fixed point */
def factorial(recursive: Long => Long) = (x: Long) => x match {
case 1 => 1
case x => x * recursive(x-1)
}
/*
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Server VM, Java 1.6.0_17).
Type in expressions to have them evaluated.
Type :help for more information.
scala> fix(factorial)(3)
res0: Long = 6
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment