Skip to content

Instantly share code, notes, and snippets.

@riobard
Created March 21, 2010 23:50
Show Gist options
  • Save riobard/339664 to your computer and use it in GitHub Desktop.
Save riobard/339664 to your computer and use it in GitHub Desktop.
Scala 2.8 generic Numeric type
// Generic factorial function
// require Scala 2.8
def factorial[T](n: T)(implicit m: Numeric[T]): T = {
import m._
if (n == zero) one else n * factorial(n-one)
// this is not tail-optimized
// StackOverFlow for n > 26,800 BigInt on my JVM (1.6 OS X)
}
// Generic factorial function (tail optimized)
// require Scala 2.8
def factorial_tail[T](n: T)(implicit m: Numeric[T]): T = {
import m._
def loop(n: T, acc: T): T = if (n <= zero) acc else loop (n - one, acc * n)
loop(n, one)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment