This morning I started my day off with another problem to learn scala better with and I wanted to only devote 30 minutes max to it as we had a busy day ahead. With this in mind, I did a simple factorial kata that I’ve done multiple times before in other languages to practice recursion. So I started off with the first spec:
import org.specs._
class FactorialSpec extends Specification{
"factorial" should {
"return 1 for n = 1" in {
Factorial(1) must be equalTo(1)
}
}
}
Of which I just returned n. I then wrote the next example which passed out of the box and finally wrote two more examples I knew would make me solve the problem.
class FactorialSpec extends Specification{
"factorial" should {
"return 1 for n = 1" in {
Factorial(1) must be equalTo(1)
}
"return 2 for n = 2" in {
Factorial(2) must be equalTo(2*1)
}
"return 6 for n = 3" in {
Factorial(3) must be equalTo(3*2*1)
}
"return 6*5*4*3*2*1 for n = 6" in {
Factorial(6) must be equalTo(6*5*4*3*2*1)
}
}
}
The first surprise I had was that scala apparently doesn’t have any ternary operator so I tried the following solution:
object Factorial extends (Int => Int){
override def apply(n:Int) = {
n * (if(n > 1) apply(n-1) else n)
}
}
This was fine and all, bit I decided to read around a bit more and see what features in scala I could apply to change this. FoldRight and foldLeft appeared to be right up my ally:
object Factorial extends (Int => Int){
override def apply(n:Int) = (1 to n).foldRight(1)(_*_)
}
foldRight works like this… it takes each element moving to the right for each one and, starting with the base number (in this case 1) multiples it to a running result (indicated by the second _). So for 4 this looks something like this:
1*1 = 1
2*1 = 2
3*2 = 6
4*6 = 24
Very interesting. There’s also a shorthand notation for foldLeft and foldRight, but so far I have decided against using it as it makes it look like code only some mathematical genius could understand.
EDIT: Okay, looks like I had it wrong. foldRight starts from the tail of the collection and works its way back while foldLeft starts from the head of the collection and works its way to the end.


foldLeft is far better than foldRight, once you didn’t have to go through your entire list and take the last element every time; foldLeft always take the list head.
As side effect, foldRight (at least used to) use lots of extra memory because it’s not tail-recursive (as foldLeft).
If the order dont make difference, you should always use foldLeft. If order makes difference, you should sort (and/or reverse) your list, then use foldLeft.