I want to rewrite a recursive function using pattern matching instead of if-else
statements, but I am getting (correct) warning messages that some parts of the code are unreachable. In fact, I am getting wrong logic evaluation.
The function I am trying to re-write is:
def pascal(c: Int, r: Int): Int =
if (c == 0)
1
else if (c == r)
1
else
pascal(c - 1, r - 1) + pascal(c, r - 1)
This function works as expected. I re-wrote it as follows using pattern matching but now the function is not working as expected:
def pascal2 (c : Int, r : Int) : Int = c match {
case 0 => 1
case r => 1
case _ => pascal2(c - 1, r - 1) + pascal2(c, r - 1)
}
Where am I going wrong?
Main
:
println("Pascal's Triangle")
for (row <- 0 to 10) {
for (col <- 0 to row)
print(pascal(col, row) + " ")
println()
}