So reading about functional programming, applications to dynamic programming, and learning Scala. I figured I would try it out with a popular example, Pascal's Triangle, tests against known values work out fine. Any tips for optimization? Am I doing anything totally wrong? Is there a way to do this with tail recursion that I'm missing? Any feedback appreciated.
def pascal(c: Int, r: Int): Int = {
// use a cache; map if (c,r) pair to value
// fill in value recursively
var cache: Map[(Int,Int), Int] = Map()
cache += ((0,0) -> 1)
var i = 0
for(i <- 1 to r){
cache += ((0,i) -> 1)
cache += ((i,i) -> 1)
}
def getPascalValue(c: Int, r: Int): Int = {
if (cache.contains((c, r))) {
cache((c, r))
} else {
cache += ((c, r) -> (getPascalValue(c, r - 1) + getPascalValue(c - 1, r - 1)))
cache((c, r))
}
}
getPascalValue(c,r)
}