Skip to content
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

Added a new Set monoid #57

Closed
wants to merge 2 commits 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
1 change: 1 addition & 0 deletions monoid-extras.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ library
Data.Monoid.Inf,
Data.Monoid.MList,
Data.Monoid.Recommend,
Data.Monoid.Set,
Data.Monoid.Split,
Data.Monoid.WithSemigroup

Expand Down
51 changes: 51 additions & 0 deletions src/Data/Monoid/Set.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{-# 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 = stimesIdempotentMonoid

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