Factorial: Difference between revisions

Content added Content deleted
Line 9,154: Line 9,154:
===Imperative===
===Imperative===
An imperative style using a mutable variable:
An imperative style using a mutable variable:
<syntaxhighlight lang="scala">def factorial(n: Int) = {
<syntaxhighlight lang="scala">
def factorial(n: Int) = {
var res = 1
var res = 1
for (i <- 1 to n)
for (i <- 1 to n)
res *= i
res *= i
res
res
}
}</syntaxhighlight>
</syntaxhighlight>


===Recursive===
===Recursive===
Using naive recursion:
Using naive recursion:
<syntaxhighlight lang="scala">def factorial(n: Int): Int =
<syntaxhighlight lang="scala">
if (n < 0) 1
def factorial(n: Int): Int =
if (n < 1) 1
else n * factorial(n - 1)</syntaxhighlight>
else n * factorial(n - 1)
</syntaxhighlight>


Using tail recursion with a helper function:
Using tail recursion with a helper function:
<syntaxhighlight lang="scala">def factorial(n: Int) = {
<syntaxhighlight lang="scala">
def factorial(n: Int) = {
@tailrec def fact(x: Int, acc: Int): Int = {
@tailrec def fact(x: Int, acc: Int): Int = {
if (x < 2) acc else fact(x - 1, acc * x)
if (x < 2) acc else fact(x - 1, acc * x)
}
}
fact(n, 1)
fact(n, 1)
}
}</syntaxhighlight>
</syntaxhighlight>


===Stdlib .product===
===Stdlib .product===
Line 9,183: Line 9,189:
===Folding===
===Folding===
Using folding:
Using folding:
<syntaxhighlight lang="scala">def factorial(n: Int) =
<syntaxhighlight lang="scala">
def factorial(n: Int) =
(2 to n).foldLeft(1)(_ * _)</syntaxhighlight>
(2 to n).foldLeft(1)(_ * _)
</syntaxhighlight>


===Using implicit functions to extend the Int type===
===Using implicit functions to extend the Int type===
Enriching the integer type to support unary exclamation mark operator and implicit conversion to big integer:
Enriching the integer type to support unary exclamation mark operator and implicit conversion to big integer:
<syntaxhighlight lang="scala">implicit def IntToFac(i : Int) = new {
<syntaxhighlight lang="scala">
implicit def IntToFac(i : Int) = new {
def ! = (2 to i).foldLeft(BigInt(1))(_ * _)
def ! = (2 to i).foldLeft(BigInt(1))(_ * _)
}
}</syntaxhighlight>
</syntaxhighlight>


{{out | Example used in the REPL}}
{{out | Example used in the REPL}}