Created
March 21, 2010 23:50
-
-
Save riobard/339664 to your computer and use it in GitHub Desktop.
Scala 2.8 generic Numeric type
This file contains 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
// 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) | |
} |
This file contains 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
// 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