--- Pascal's triangle is the arrangement of binomial coefficients in a triangular array.
--- The rows of the triangle are staggered so that each number can be computed as the
--- sum of the numbers to the left and right in the previous row.
--- The function ;pascal; produces the triangle to a given depth.
module PascalsTriangle;

open import Stdlib.Prelude;

zipWith :
  {A : Type}{B : Type}{C : Type}(ABC)List AList BList C;
zipWith f nil _ := nil;
zipWith f _ nil := nil;
zipWith f (x :: xs) (y :: ys) := f x y :: zipWith f xs ys;

--- Return a list of repeated applications of a given function
iterate : {A : Type}Nat(AA)AList A;
iterate zero _ _ := nil;
iterate (suc n) f a := a :: iterate n f (f a);

--- Produce a singleton List
singleton : {A : Type}AList A;
singleton a := a :: nil;

--- Concatenates a list of strings
--- ;concat (("a" :: nil) :: "b" :: nil); evaluates to ;"a" :: "b" :: nil;
concat : List StringString;
concat := foldl (++str) "";

intercalate : StringList StringString;
intercalate sep xs := concat (intersperse sep xs);

--- Joins a list of strings with the newline character
unlines : List StringString;
unlines := intercalate "\n";

showList : List NatString;
showList xs := "[" ++str intercalate "," (map natToString xs) ++str "]";

--- Compute the next row of Pascal's triangle
pascalNextRow : List NatList Nat;
pascalNextRow row :=
  zipWith (+) (singleton zero ++ row) (row ++ singleton zero);

--- Produce Pascal's triangle to a given depth
pascal : NatList (List Nat);
pascal rows := iterate rows pascalNextRow (singleton 1);

main : IO;
main := printStringLn (unlines (map showList (pascal 10)));
Last modified on 2023-04-19 22:00 UTC