Last active
July 12, 2016 06:57
-
-
Save pestilence669/65ee1dd8dd749a87afbd32819589feba to your computer and use it in GitHub Desktop.
Various ways to implement factorial in Scala
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
#!/bin/sh | |
exec scala "$0" "$@" | |
!# | |
// vim: set ts=2 sw=2 et fileencoding=utf-8: | |
import java.lang.reflect.Method | |
import scala.annotation.tailrec | |
import scala.language.postfixOps | |
/** | |
* Various ways to implement factorial in Scala | |
*/ | |
object Factorial { | |
val runnableNameRX = "^factorial\\d+$".r pattern | |
def isRunnableName(f: Method) = runnableNameRX matcher(f getName) matches | |
def methods = this.getClass getMethods | |
def methodsToRun = methods filter isRunnableName | |
def methodName(f: Method) = f getName | |
////////////////////////////////////////////////////////////////////////////// | |
def factorial0(n: Int): Int = { | |
var a: Int = 1; | |
var i: Int = 2; | |
while (i <= n) { | |
a *= i; | |
i += 1; | |
} | |
return a; | |
} | |
def factorial1(n: Int) = { | |
@tailrec | |
def inner(n: Int, retval: Int = 1): Int = n match { | |
case i if i < 2 ⇒ | |
retval | |
case i ⇒ | |
inner(i - 1, i * retval) | |
} | |
inner(n) | |
} | |
def factorial2(n: Int) = Range(2, n + 1).foldLeft(1)((a, v) ⇒ a * v) | |
def factorial3(n: Int) = (1 /: (2 to n)) (_ * _) | |
def factorial4(n: Int) = 1 to n product | |
////////////////////////////////////// | |
implicit class IntDecorator(val n: Int) { | |
def ! = factorial4(n) | |
} | |
def factorial5(n: Int) = n! | |
def factorial6(n: Int) = IntDecorator(n).! | |
////////////////////////////////////////////////////////////////////////////// | |
def main(args: Array[String]): Unit = { | |
val fact_n = if (args.length > 0) args(0) toInt else 14 | |
(methodsToRun sortBy methodName) foreach { f ⇒ | |
val result = f.invoke(this, fact_n.asInstanceOf[AnyRef]) | |
println(s"${f getName}($fact_n) == $result") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment