Vec.agda 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. module Lib.Vec where
  2. open import Common.Nat
  3. open import Lib.Fin
  4. open import Common.Unit
  5. import Common.List as List; open List using (List ; [] ; _∷_)
  6. data Vec (A : Set) : Nat → Set where
  7. _∷_ : {n : Nat} → A → Vec A n → Vec A (suc n)
  8. [] : Vec A zero
  9. infixr 30 _++_
  10. _++_ : {A : Set}{m n : Nat} → Vec A m → Vec A n → Vec A (m + n)
  11. [] ++ ys = ys
  12. (x ∷ xs) ++ ys = x ∷ (xs ++ ys)
  13. snoc : {A : Set}{n : Nat} → Vec A n → A → Vec A (suc n)
  14. snoc [] e = e ∷ []
  15. snoc (x ∷ xs) e = x ∷ snoc xs e
  16. -- Recursive length.
  17. length : {A : Set}{n : Nat} → Vec A n → Nat
  18. length [] = zero
  19. length (x ∷ xs) = 1 + length xs
  20. length' : {A : Set}{n : Nat} → Vec A n → Nat
  21. length' {n = n} _ = n
  22. zipWith3 : ∀ {A B C D n} → (A → B → C → D) → Vec A n → Vec B n → Vec C n → Vec D n
  23. zipWith3 f [] [] [] = []
  24. zipWith3 f (x ∷ xs) (y ∷ ys) (z ∷ zs) = f x y z ∷ zipWith3 f xs ys zs
  25. zipWith : ∀ {A B C n} → (A → B → C) → Vec A n → Vec B n → {u : Unit} → Vec C n
  26. zipWith _ [] [] = []
  27. zipWith f (x ∷ xs) (y ∷ ys) = f x y ∷ zipWith f xs ys {u = unit}
  28. _!_ : ∀ {A n} → Vec A n → Fin n → A
  29. (x ∷ xs) ! fz = x
  30. (_ ∷ xs) ! fs n = xs ! n
  31. [] ! ()
  32. -- Update vector at index
  33. _[_]=_ : {A : Set}{n : Nat} → Vec A n → Fin n → A → Vec A n
  34. (a ∷ as) [ fz ]= e = e ∷ as
  35. (a ∷ as) [ fs n ]= e = a ∷ (as [ n ]= e)
  36. [] [ () ]= e
  37. map : ∀ {A B n}(f : A → B)(xs : Vec A n) → Vec B n
  38. map f [] = []
  39. map f (x ∷ xs) = f x ∷ map f xs
  40. -- Vector to List, forget the length.
  41. forgetL : {A : Set}{n : Nat} → Vec A n → List A
  42. forgetL [] = []
  43. forgetL (x ∷ xs) = x ∷ forgetL xs
  44. -- List to Vector, "rem"member the length.
  45. rem : {A : Set}(xs : List A) → Vec A (List.length xs)
  46. rem [] = []
  47. rem (x ∷ xs) = x ∷ rem xs