Last night I completed this weeks Scala Kata to generate Pascal’s Triangle using a List of Lists. Although it works, I’d like to see if there is a better “scala way” to get it done. I’ve also discovered that List in scala is immutable so all those times I’m adding elements to the List I’m not really adding to it… I’m creating a new list and re-assigning it to the variable. I also see it’s going to take awhile to break free of the conditioning that java has put me through.
Don’t look if you still want to do the kata, otherwise take a gander and let me know how I can improve the internal design.
import org.specs._
object PascalsTriangleSpec extends Specification{
"Pascals Triangle Generator" should{
val generator = new PascalTriangleGenerator
"return a List with List(1) for 1" in {
val result = generator.generate(1)
result must be equalTo(List(List(1)))
}
"return List(1), List(1,1) for 2" in {
val result = generator.generate(2)
result must be equalTo(List(List(1), List(1,1)))
}
"return List(1), List(1,1), and List(1,2,1) for 3" in {
generator.generate(3) must be equalTo(List(
List(1),
List(1,1),
List(1,2,1)))
}
"generate to the 4th layer" in {
generator.generate(4) must be equalTo(List(
List(1),
List(1,1),
List(1,2,1),
List(1,3,3,1)))
}
"generate to the 5th layer" in {
generator.generate(5) must be equalTo(List(
List(1),
List(1,1),
List(1,2,1),
List(1,3,3,1),
List(1,4,6,4,1)))
}
"generate to the 6th layer" in {
generator.generate(6) must be equalTo(List(
List(1),
List(1,1),
List(1,2,1),
List(1,3,3,1),
List(1,4,6,4,1),
List(1,5,10,10,5,1)))
}
}
}
class PascalTriangleGenerator{
def generate(n:Int) = {
var triangle = List(List(1))
(2 to n).foreach( i=> triangle += createNextLayer(triangle.last))
triangle
}
private def createNextLayer(previous:List[Int]) = {
var list = List(1)
for(j <- 1 until previous.length){
list += previous(j)+previous(j-1)
}
list+1
}
}


Scala would be to use folds, although I can’t offer a solution.
I’ve tried to use folds in Haskell which is kinda similar to Scala. Function that generates the next row looks ugly:
getRow xs = foldr appendPascal (0,[]) xs where
appendPascal x y = (x, ((x + fst y): snd y))
Thanks for the Kata. My solution is at http://synesso.posterous.com/pascals-triangle-kata
My solution to this kata is here: http://synesso.posterous.com/pascals-triangle-kata
@synapse
It’s actually better represented as an unfold not a fold:
nextRow r = Just (r,nr) where xr = 0:r ; nr = zipWith (+) xr $ reverse xr
pascal = unfoldr nextRow [1]
take 5 pascal
or more succint using iterate
nextRow’ r = zipWith (+) xr $ reverse xr where xr = 0:r
pascal’ = iterate nextRow’ [1]
take 5 pascal’
[...] Nachtrag Wenn wir schonmal beim Etwas-Besseres-Finden sind: Ich bin gerade über das Blog von James Carr gestolpert. Hier meine Lösung zu seiner Aufgabe, das Pascalsche Dreieck als Liste von Listen zu berechnen: [...]
My solution: http://dgronau.wordpress.com/2010/07/11/block-trick/ (last listing)