Pascal's triangle: Difference between revisions

Added Haskell example
(Ada)
(Added Haskell example)
Line 47:
end Pascals_Triangle;
</ada>
 
=={{header|Haskell}}==
 
An approach using the "think in whole lists" principle: Each row in
the triangle can be calculated from the previous row by adding a
shifted version of itself to it, keeping the ones at the ends. The
Prelude function ''zipWith'' can be used to add two lists, but it
won't keep the old values when one list is shorter. So we need a
similar function
 
<pre>
zapWith :: (a -> a -> a) -> [a] -> [a] -> [a]
zapWith f xs [] = xs
zapWith f [] ys = ys
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys
</pre>
 
Now we can shift a list and add it to itself, extending it by keeping
the ends:
 
<pre>
extendWith f [] = []
extendWith f xs@(x:ys) = x : zapWith f xs ys
</pre>
 
And for the whole (infinite) triangle, we just iterate this operation,
starting with the first row:
 
<pre>
pascal = iterate (extendWith (+)) [1]
</pre>
 
For the first ''n'' rows, we just take the first ''n'' elements from this
list, as in
 
<pre>
*Main> take 6 pascal
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]
</pre>
 
=={{header|Java}}==
Anonymous user