From 748fe299428529ac76b809c5e0fbf4dc5fd81670 Mon Sep 17 00:00:00 2001 From: BlackCapCoder Date: Thu, 24 Oct 2024 04:25:59 +0200 Subject: [PATCH 1/2] Added Set --- monoid-extras.cabal | 1 + src/Data/Monoid/Set.hs | 53 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/Data/Monoid/Set.hs diff --git a/monoid-extras.cabal b/monoid-extras.cabal index 6a5d738..93dd6c2 100644 --- a/monoid-extras.cabal +++ b/monoid-extras.cabal @@ -33,6 +33,7 @@ library Data.Monoid.Inf, Data.Monoid.MList, Data.Monoid.Recommend, + Data.Monoid.Set, Data.Monoid.Split, Data.Monoid.WithSemigroup diff --git a/src/Data/Monoid/Set.hs b/src/Data/Monoid/Set.hs new file mode 100644 index 0000000..721f406 --- /dev/null +++ b/src/Data/Monoid/Set.hs @@ -0,0 +1,53 @@ +{-# LANGUAGE DeriveDataTypeable #-} +{-# LANGUAGE DeriveFoldable #-} +{-# LANGUAGE DeriveFunctor #-} +{-# LANGUAGE DeriveTraversable #-} +{-# LANGUAGE MagicHash #-} +{-# OPTIONS_GHC -fno-warn-unused-imports #-} + +module Data.Monoid.Set where + +import Data.Data +import Data.Semigroup +import Data.Foldable +import Data.Traversable + +import GHC.Exts (isTrue#, dataToTag#) +import Unsafe.Coerce (unsafeCoerce) + +---- + +-- | @Set@ is like @Maybe@, but the value can either be +-- unspecified with @Unset@, or explicitly cleared with @Clear@ +data Set a + = Unset + | Set a + | Clear + deriving (Data, Typeable, Show, Read, Functor, Foldable, Traversable) + + +-- | The right-hand-side or "newer" value is prefered, unless it +-- is Unset, in which case the old value is left unchanged +instance Semigroup (Set a) where + + l <> Unset = l + _ <> r = r + + stimes n s + | n < 1 = Unset + | let = s + +instance Monoid (Set a) where + mempty = Unset + + +isSet :: Set a -> Bool +isSet s = isTrue# (dataToTag# s) + +maybeToSet :: Maybe a -> Set a +maybeToSet = unsafeCoerce + +setToMaybe :: Set a -> Maybe a +setToMaybe (Set a) = Just a +setToMaybe _ = Nothing + From 0bba66cffb36e96c042b0af01916ece5b3bfc461 Mon Sep 17 00:00:00 2001 From: BlackCapCoder Date: Thu, 24 Oct 2024 05:18:09 +0200 Subject: [PATCH 2/2] prefer stimesIdempotentMonoid --- src/Data/Monoid/Set.hs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Data/Monoid/Set.hs b/src/Data/Monoid/Set.hs index 721f406..f4ba34a 100644 --- a/src/Data/Monoid/Set.hs +++ b/src/Data/Monoid/Set.hs @@ -33,9 +33,7 @@ instance Semigroup (Set a) where l <> Unset = l _ <> r = r - stimes n s - | n < 1 = Unset - | let = s + stimes = stimesIdempotentMonoid instance Monoid (Set a) where mempty = Unset