Factorial: Difference between revisions

relabel recursive example; add tail-recursive example and subheaders
(→‎Scala: First example is imperative)
(relabel recursive example; add tail-recursive example and subheaders)
Line 5,837:
 
=={{header|Scala}}==
 
===Imperative===
An imperative style using a mutable variable:
<lang scala>def factorial(n: Int)={
Line 5,844 ⟶ 5,846:
res
}</lang>
 
Using tail recursion:
===Recursive===
Using tailnaive recursion:
<lang scala>def factorial(n: Int) =
if (n == 0) 1
else n * factorial(n-1)</lang>
 
Using tail recursion with a helper function:
<lang scala>def factorial(n: Int) = {
def fact(x: Int, acc: Int): Int = {
if (x < 2) acc else fact(x - 1, acc * x)
}
fact(n, 1)
}</lang>
 
===Folding===
Using folding:
<lang scala>def factorial(n: Int) =
(2 to n).foldLeft(1)(_ * _)</lang>
 
===Using implicit functions to extend the Int type===
Enriching the integer type to support unary exclamation mark operator and implicit conversion to big integer:
<lang scala>implicit def IntToFac(i : Int) = new {
Anonymous user