std:Vec
lib/Vec.omg
lib/Vec.omg84 lines
1{- Vectors: lists whose length is part of their type.
2
3 `Vec a n` is defined by recursion on `n`, which computes a /type/ in the
4 universe of `a`, `Type l`:
5
6 Vec a 0 = unit @l
7 Vec a (n + 1) = a * Vec a n
8
9 so a vector of length 2 is literally a pair `(x, (y, {=}))`, and the type
10 checker knows the length of every vector. `head` cannot be applied to an
11 empty vector, and `zip` only accepts vectors of the same length. The
12 elements can be of any universe: `Vec Type 2` is a vector of two types.
13-}
14
15let Vec
16 : forall {l : Level} -> Type l -> Natural -> Type l
17 = \{l} a n ->
18 Natural/elim
19 (\(_ : Natural) -> Type l)
20 (unit @l)
21 (\(_ : Natural) (rest : Type l) -> a * rest)
22 n
23
24let nil : forall {l : Level} {a : Type l} -> Vec a 0 = {=}
25
26let cons
27 : forall {l : Level} {a : Type l} {n : Natural} -> a -> Vec a n -> Vec a (n + 1)
28 = \x xs -> (x, xs)
29
30let head : forall {l : Level} {a : Type l} {n : Natural} -> Vec a (n + 1) -> a = \xs -> xs.1
31
32let tail
33 : forall {l : Level} {a : Type l} {n : Natural} -> Vec a (n + 1) -> Vec a n
34 = \xs -> xs.2
35
36-- replicate n x is the vector of n copies of x.
37let replicate
38 : forall {l : Level} {a : Type l} (n : Natural) -> a -> Vec a n
39 = \{l} {a} n x ->
40 Natural/elim
41 (\(k : Natural) -> Vec a k)
42 {=}
43 (\(k : Natural) (rest : Vec a k) -> (x, rest))
44 n
45
46let toList
47 : forall {l : Level} {a : Type l} (n : Natural) -> Vec a n -> List a
48 = \{l} {a} n ->
49 Natural/elim
50 (\(k : Natural) -> Vec a k -> List a)
51 (\(_ : unit @l) -> ([] : List a))
52 (\(k : Natural) (rest : Vec a k -> List a) (xs : Vec a (k + 1)) -> [ xs.1 ] # rest xs.2)
53 n
54
55let map
56 : forall {la lb : Level} {a : Type la} {b : Type lb} (n : Natural)
57 -> (a -> b)
58 -> Vec a n
59 -> Vec b n
60 = \{la} {lb} {a} {b} n f ->
61 Natural/elim
62 (\(k : Natural) -> Vec a k -> Vec b k)
63 (\(_ : unit @la) -> {=})
64 (\(k : Natural) (rest : Vec a k -> Vec b k) (xs : Vec a (k + 1)) -> (f xs.1, rest xs.2))
65 n
66
67-- Vectors of the same length are zipped without losing any element.
68let zip
69 : forall {la lb : Level} {a : Type la} {b : Type lb} (n : Natural)
70 -> Vec a n
71 -> Vec b n
72 -> Vec (a * b) n
73 = \{la} {lb} {a} {b} n ->
74 Natural/elim
75 (\(k : Natural) -> Vec a k -> Vec b k -> Vec (a * b) k)
76 (\(_ : unit @la) (_ : unit @lb) -> {=})
77 (\(k : Natural)
78 (rest : Vec a k -> Vec b k -> Vec (a * b) k)
79 (xs : Vec a (k + 1))
80 (ys : Vec b (k + 1)) ->
81 ((xs.1, ys.1), rest xs.2 ys.2))
82 n
83
84in { Vec, nil, cons, head, tail, replicate, toList, map, zip }