From d803af10aab0850170eaadeea30264a803f07122 Mon Sep 17 00:00:00 2001 From: Steve Dunham Date: Sat, 31 Jan 2026 16:29:16 -0800 Subject: [PATCH] Add Foldable class --- TODO.md | 2 +- src/Data/SortedMap.newt | 5 +++++ src/Prelude.newt | 22 +++++++++++++++------- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/TODO.md b/TODO.md index d9248f4..da009eb 100644 --- a/TODO.md +++ b/TODO.md @@ -13,7 +13,7 @@ - I can do `let f : ... = \ a b c => ...`. But it doesn't work for recursion and cases are awkward. - [x] Erasure checking happens at compile time and isn't surfaced to editor.. - [ ] Erasure issue during AoC from case building replacing a non-erased value with erased. -- [ ] Add Foldable? +- [x] Add Foldable - [ ] Maybe return constraints instead of solving metas during unification - We already return non-meta constraints for work on the LHS. - We might get into a situation where solving immediately would have gotten us more progress? diff --git a/src/Data/SortedMap.newt b/src/Data/SortedMap.newt index 8443cee..5eb8895 100644 --- a/src/Data/SortedMap.newt +++ b/src/Data/SortedMap.newt @@ -220,3 +220,8 @@ foldMap f m ((a,b) :: xs) = case lookupMap a m of listValues : ∀ k v. SortedMap k v → List v listValues sm = map snd $ toList sm + +instance ∀ k. Foldable (SortedMap k) where + foldr f z m = foldr f z (listValues m) + foldl f z m = foldl f z (listValues m) + diff --git a/src/Prelude.newt b/src/Prelude.newt index 662db97..3a5d37e 100644 --- a/src/Prelude.newt +++ b/src/Prelude.newt @@ -476,15 +476,23 @@ pfunc stringToInt : String → Int := `(s) => { return rval }` --- TODO - add Foldable +class Foldable (m : U → U) where + foldl : ∀ a b. (b → a → b) → b → m a → b + foldr : ∀ a b. (a → b → b) → b → m a → b -foldl : ∀ A B. (B → A → B) → B → List A → B -foldl f acc Nil = acc -foldl f acc (x :: xs) = foldl f (f acc x) xs +instance Foldable List where + foldl f acc Nil = acc + foldl f acc (x :: xs) = foldl f (f acc x) xs -foldr : ∀ a b. (a → b → b) → b → List a → b -foldr f b Nil = b -foldr f b (x :: xs) = f x (foldr f b xs) + foldr f b Nil = b + foldr f b (x :: xs) = f x (foldr f b xs) + +instance Foldable SnocList where + foldl f acc Lin = acc + foldl f acc (xs :< x) = f (foldl f acc xs) x + + foldr f b Lin = b + foldr f b (xs :< x) = foldr f (f x b) xs infixl 9 _∘_ _∘_ : ∀ A B C. (B → C) → (A → B) → A → C