From a7b3ee033e3461b3682ebb3aff37e6d659321c74 Mon Sep 17 00:00:00 2001 From: Hans-Peter Deifel <hpd@hpdeifel.de> Date: Fri, 8 Mar 2019 09:26:24 +0100 Subject: [PATCH] SumBag: Implement Foldable --- src/Data/SumBag.hs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/Data/SumBag.hs b/src/Data/SumBag.hs index 12267b5..4a36612 100644 --- a/src/Data/SumBag.hs +++ b/src/Data/SumBag.hs @@ -13,6 +13,7 @@ module Data.SumBag ) where import Prelude hiding (sum, min, elem) +import Data.Foldable hiding (sum,elem) import qualified Data.List.NonEmpty as NE type SumBag a = Tree a @@ -20,10 +21,26 @@ type SumBag a = Tree a data Tree a = Leaf | Node (MetaData a) (Element a) (Tree a) (Tree a) deriving (Show) +type role Tree nominal + instance (Ord a, Eq a) => Eq (Tree a) where x == y = toAscList x == toAscList y -type role Tree nominal +-- TODO There are a few functions from foldable that can be implemented way more +-- efficiently. +-- +-- Notably 'minimum' and 'maximum', but also explicit recursion instead of +-- conversions to lists in a lot of cases. +instance Foldable Tree where + foldMap f = foldMap f . toAscList + {-# INLINE foldMap #-} + + fold = sum + {-# INLINE fold #-} + + toList = toAscList + {-# INLINE toList #-} + data MetaData a = MetaData { nodeSize :: Int @@ -81,7 +98,7 @@ delete a (Node _ e left right) let (min, rest) = delmin right in balance1 min left rest -toAscList :: Ord a => SumBag a -> [a] +toAscList :: SumBag a -> [a] toAscList bag = helper bag [] where helper Leaf accu = accu helper (Node _ e left right) accu = -- GitLab