Pascal's triangle: Difference between revisions

Scala contribution maintained.
(Rust)
(Scala contribution maintained.)
Line 4,200:
 
=={{header|Scala}}==
===Functional solutions===
Simple recursive row definition:
====Summing: Recursive row definition====
<lang scala>
def tri(row: Int): List[Int] = { row match {
case 1 =>row List(1)match {
case 1 => List(1)
case n: Int => List(1) ::+: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :::+ List(1)
}
}</lang>
}
</lang>
Function to pretty print n rows:
<lang scala>def prettytriprettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println}
<lang scala>
 
def prettytri(n:Int) = (1 to n) foreach {i=>print(" "*(n-i)); tri(i) map (c=>print(c+" ")); println}
prettyTri(5)</lang>
prettytri(5)
{{Out}}
</lang>
<pre> 1
Outputs:
1 3 3 1 1
<pre>
1 2 1
1 3 3 1 1
1 4 16 24 1 </pre>
====Summing: Scala Stream (Recursive & Memoization)====
1 3 3 1
<lang Scala>object Blaise extends App {
1 4 6 4 1
def pascalTriangle(): Stream[Vector[Int]] =
</pre>
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1)
 
val output = pascalTriangle().take(15).map(_.mkString(" "))
val longest = output.last.length
 
println("Pascal's Triangle")
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line"))
}</lang scala>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/8VqiX0P/1 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/c3dDWMCcT3eoydy6QJcWCw Scastie (JVM)].
 
=={{header|Scheme}}==
Anonymous user