Skip to content

sum as an accumulating fold; sum-++ by way of fold-++ #1712

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/Data/Vec/Base.agda
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,11 @@ foldl₁ _⊕_ (x ∷ xs) = foldl _ _⊕_ x xs

-- Special folds

fold-sum : ℕ → Vec ℕ n → ℕ
fold-sum n = foldr′ _+_ n

sum : Vec ℕ n → ℕ
sum = foldr _ _+_ 0
sum = fold-sum 0

count : ∀ {P : Pred A p} → Decidable P → Vec A n → ℕ
count P? [] = zero
Expand Down
16 changes: 11 additions & 5 deletions src/Data/Vec/Properties.agda
Original file line number Diff line number Diff line change
Expand Up @@ -857,12 +857,18 @@ map-ʳ++ {ys = ys} f xs = begin
------------------------------------------------------------------------
-- sum

sum-fold-sum : ∀ (xs : Vec ℕ m) n → fold-sum n xs ≡ sum xs + n
sum-fold-sum [] n = refl
sum-fold-sum (x ∷ xs) n = begin
x + fold-sum n xs ≡⟨ cong (x +_) (sum-fold-sum xs n) ⟩
x + (sum xs + n) ≡˘⟨ +-assoc x (sum xs) n ⟩
sum (x ∷ xs) + n ∎

sum-++ : ∀ (xs : Vec ℕ m) → sum (xs ++ ys) ≡ sum xs + sum ys
sum-++ {_} [] = refl
sum-++ {ys = ys} (x ∷ xs) = begin
x + sum (xs ++ ys) ≡⟨ cong (x +_) (sum-++ xs) ⟩
x + (sum xs + sum ys) ≡˘⟨ +-assoc x (sum xs) (sum ys) ⟩
sum (x ∷ xs) + sum ys ∎
sum-++ {ys = ys} xs = begin
sum (xs ++ ys) ≡⟨ foldr-++ _ _+_ xs ⟩
fold-sum (sum ys) xs ≡⟨ sum-fold-sum xs (sum ys) ⟩
sum xs + sum ys ∎

------------------------------------------------------------------------
-- replicate
Expand Down