Triangular Arrays
The following type declaration allows us to represente triangular arrays:
The i- line (starting from the top) contains a tuple of i
elements of type A.
Inductive triangular (A B : Type) :=
| base : B -> triangular A B
| line : B -> triangular A (A * B) -> triangular A B.
Definition triangle (A: Type) := triangular A A.
Arguments base {A B} _.
Arguments line {A B} _ _.
Example t1 : triangle nat :=
base 6.
Example t2 : triangle nat :=
line 5
(base (1, 1)).
Example t3 :triangle nat :=
line 6
(line (5, 3)
(line (5, (7, 8))
(base (1, (2, (3, 4)))))).
Task
Define functions for computing:
- The height of a triangle of type triangle A . For instance, t3's heigth is
4.
- The bottom line of a triangle : For instance, the list (1::2::3::4::nil)
for t3
- The leftmost colummn of a triangle : For instance, the list (6::5::5::1::nil)
for t3
- The rightmost diagonal of a triangle : For instance, the list (6::3::8::4::nil)
for t3
- A concatenation of all the lines of a triangle :
For instance, the list 6 :: 5 :: 3 :: 5 :: 7 :: 8 :: 1 :: 2 :: 3 :: 4 :: nil
for t3
Define a function that returns a triangle of given height, such that all the cells
contain the same given element.
Acknowledgements
This example of using inductive types with a varying parameter (here B)
was given to us by Ralph Mattes.
Solution
Look at this file
Extra work
Define the same structure as a type depending on the heigth of the triangle. Instead
of lists, you should return vectors.
Can you write a function that builds Pascal's triangle?