{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeFamilies #-}
-- | 'InsOrdHashSet' is like 'HashSet', but it folds in insertion order.
--
-- This module interface mimics "Data.HashSet", with some additions.
module Data.HashSet.InsOrd (
InsOrdHashSet,
-- * Construction
empty,
singleton,
-- * Basic interface
null,
size,
member,
insert,
delete,
-- * Combine
union,
-- * Transformations
map,
-- ** Unordered
-- * Difference and intersection
difference,
intersection,
-- * Folds
-- ** Unordered
-- * Filter
filter,
-- * Conversions
toList,
fromList,
toHashSet,
fromHashSet,
-- * Debugging
valid,
)where
import Prelude
(Bool, Eq ((==)), Int, Ord (compare, max, min), const, flip, fmap, fst, id,
otherwise, return, snd, zip, ($), (&&), (+), (.), (<$>), (<), (>),
(>=), (||))
import Control.Arrow (first)
import Control.DeepSeq (NFData (..))
import Data.Data
(Constr, Data (..), DataType, Fixity (Prefix), gcast1, mkConstr,
mkDataType)
import Data.Foldable (Foldable (foldMap), all)
import Data.Hashable (Hashable (..))
import Data.List (nub, sortBy)
import Data.Monoid (Monoid (..))
import Data.Ord (comparing)
import Data.Semigroup (Semigroup (..))
import Text.ParserCombinators.ReadPrec (prec)
import Text.Read
(Lexeme (..), Read (..), lexP, parens, readListPrecDefault)
import Text.Show (Show (..), showParen, showString)
import Control.Monad.Trans.State.Strict (State, runState, state)
import qualified Data.Aeson as A
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.HashSet (HashSet)
import qualified Data.HashSet as HashSet
import qualified Data.Foldable
import qualified GHC.Exts as Exts
import qualified Control.DeepSeq as NF
import Data.HashMap.InsOrd.Internal
-------------------------------------------------------------------------------
-- InsOrdHashSet
-------------------------------------------------------------------------------
-- | A 'HashSet' that keeps its elements in insertion order.
--
-- A new element is added at the end. Inserting an element that is already
-- present keeps its position. Deleting an element and inserting it again
-- moves it to the end.
data InsOrdHashSet k = InsOrdHashSet
{ _getIndex :: !Int
, getInsOrdHashSet :: !(HashMap k Int)
}
-- | Presented as a single virtual constructor @fromList@ applied to the
-- elements in insertion order.
instance (Data k, Eq k, Hashable k) => Data (InsOrdHashSet k) where
gfoldl f z m = z fromList `f` toList m
toConstr _ = fromListConstr
gunfold k z _ = k (z fromList)
dataTypeOf _ = insOrdHashSetDataType
dataCast1 f = gcast1 f
fromListConstr :: Constr
fromListConstr = mkConstr insOrdHashSetDataType "fromList" [] Prefix
insOrdHashSetDataType :: DataType
insOrdHashSetDataType =
mkDataType "Data.HashSet.InsOrd.InsOrdHashSet" [fromListConstr]
-- | @since 0.2.5
instance NFData k => NFData (InsOrdHashSet k) where
rnf (InsOrdHashSet _ hs) = rnf hs
-- | @since 0.2.5
instance NF.NFData1 InsOrdHashSet where
liftRnf rnf1 (InsOrdHashSet _ m) = NF.liftRnf2 rnf1 rnf m
-- | Compares elements in insertion order; the absolute values of the
-- internal insertion stamps are ignored.
instance Eq k => Eq (InsOrdHashSet k) where
a == b = toList a == toList b
-- | Compares the elements lexicographically, in insertion order.
--
-- @since FIXME
instance Ord k => Ord (InsOrdHashSet k) where
compare a b = compare (toList a) (toList b)
instance Show k => Show (InsOrdHashSet k) where
showsPrec d m = showParen (d > 10) $
showString "fromList " . showsPrec 11 (toList m)
instance (Eq k, Hashable k, Read k) => Read (InsOrdHashSet k) where
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
instance (Eq k, Hashable k) => Semigroup (InsOrdHashSet k) where
(<>) = union
instance (Eq k, Hashable k) => Monoid (InsOrdHashSet k) where
mempty = empty
instance Foldable InsOrdHashSet where
-- in newer base only
-- length = length . getInsOrdHashSet
foldMap f = foldMap f . toList
null = null
toList = toList
length = size
-- | @'hashWithSalt' salt . 'toHashSet' = 'hashWithSalt' salt@.
instance Hashable k => Hashable (InsOrdHashSet k) where
hashWithSalt salt = hashWithSalt salt . toHashSet
instance (Eq k, Hashable k) => Exts.IsList (InsOrdHashSet k) where
type Item (InsOrdHashSet k) = k
fromList = fromList
toList = toList
-------------------------------------------------------------------------------
-- Aeson
-------------------------------------------------------------------------------
instance A.ToJSON a => A.ToJSON (InsOrdHashSet a) where
toJSON = A.toJSON . toList
toEncoding = A.toEncoding . toList
instance (Eq a, Hashable a, A.FromJSON a) => A.FromJSON (InsOrdHashSet a) where
parseJSON v = fromList <$> A.parseJSON v
-------------------------------------------------------------------------------
-- Construction
-------------------------------------------------------------------------------
empty :: InsOrdHashSet k
empty = InsOrdHashSet 0 HashMap.empty
{-# INLINABLE empty #-}
singleton :: Hashable k => k -> InsOrdHashSet k
singleton k = InsOrdHashSet 1 (HashMap.singleton k 0)
{-# INLINABLE singleton #-}
-------------------------------------------------------------------------------
-- Basic interface
-------------------------------------------------------------------------------
null :: InsOrdHashSet k -> Bool
null = HashMap.null . getInsOrdHashSet
{-# INLINABLE null #-}
size :: InsOrdHashSet k -> Int
size = HashMap.size . getInsOrdHashSet
{-# INLINABLE size #-}
member :: (Eq k, Hashable k) => k -> InsOrdHashSet k -> Bool
member k = HashMap.member k . getInsOrdHashSet
{-# INLINABLE member #-}
-- | Add an element to the end of the set.
--
-- An element that is already present keeps its position.
insert :: (Eq k, Hashable k) => k -> InsOrdHashSet k -> InsOrdHashSet k
insert k s@(InsOrdHashSet i m)
| HashMap.member k m = s
| otherwise = InsOrdHashSet (i + 1) (HashMap.insert k i m)
delete :: (Eq k, Hashable k) => k -> InsOrdHashSet k -> InsOrdHashSet k
delete k (InsOrdHashSet i m) = InsOrdHashSet i (HashMap.delete k m)
-------------------------------------------------------------------------------
-- Combine
-------------------------------------------------------------------------------
-- | The union of two sets: the elements of the first set in their order,
-- followed by the elements of the second set that are not in the first, in
-- their order.
union
:: (Eq k, Hashable k)
=> InsOrdHashSet k -> InsOrdHashSet k -> InsOrdHashSet k
union (InsOrdHashSet i a) (InsOrdHashSet j b) =
mk $ HashMap.union a b'
where
mk | i >= 0xfffff || j >= 0xfffff = fromHashMapInt
| otherwise = InsOrdHashSet (i + j)
b' = HashMap.map (+ i) b
-------------------------------------------------------------------------------
-- Transformations
-------------------------------------------------------------------------------
-- | Map a function over the elements of the set.
--
-- If @f@ maps several elements to the same value, the result takes the
-- position of the earliest of them, so @map f = 'fromList' . fmap f . 'toList'@.
map :: (Hashable b, Eq b) => (a -> b) -> InsOrdHashSet a -> InsOrdHashSet b
map f (InsOrdHashSet i m) = InsOrdHashSet i
$ HashMap.fromListWith min . fmap (first f) . HashMap.toList
$ m
{-# INLINABLE map #-}
-------------------------------------------------------------------------------
-- Difference and intersection
-------------------------------------------------------------------------------
difference :: (Eq a, Hashable a) => InsOrdHashSet a -> InsOrdHashSet a -> InsOrdHashSet a
difference (InsOrdHashSet i a) (InsOrdHashSet _ b) =
InsOrdHashSet i $ HashMap.difference a b
-- | The intersection of two sets: the elements of the first set that are
-- also in the second set, in the order of the first set.
intersection :: (Eq a, Hashable a) => InsOrdHashSet a -> InsOrdHashSet a -> InsOrdHashSet a
intersection (InsOrdHashSet i a) (InsOrdHashSet _ b) =
InsOrdHashSet i $ HashMap.intersection a b
-------------------------------------------------------------------------------
-- Filter
-------------------------------------------------------------------------------
filter :: (a -> Bool) -> InsOrdHashSet a -> InsOrdHashSet a
filter p (InsOrdHashSet i m) = InsOrdHashSet i $
HashMap.filterWithKey (\k _ -> p k) m
-------------------------------------------------------------------------------
-- Conversions
-------------------------------------------------------------------------------
-- | Construct a set from a list of elements.
--
-- If an element occurs more than once, it keeps the position of its first
-- occurrence.
--
-- >>> fromList [1, 2, 1]
-- fromList [1,2]
fromList :: (Eq k, Hashable k) => [k] -> InsOrdHashSet k
fromList xs = InsOrdHashSet counter m
where
m = HashMap.fromListWith (\_ i -> i) (zip xs [0 ..])
counter = HashMap.foldl' (\i j -> max i (j + 1)) 0 m
toList :: InsOrdHashSet k -> [k]
toList
= fmap fst
. sortBy (comparing snd)
. HashMap.toList
. getInsOrdHashSet
-- | Convert a 'HashSet'. The insertion order of the result is the order of
-- 'HashSet.toList', which is unspecified.
fromHashSet :: HashSet k -> InsOrdHashSet k
fromHashSet s = case numberWith const (HashSet.toMap s) of
(n, m) -> InsOrdHashSet n m
toHashSet :: InsOrdHashSet k -> HashSet k
toHashSet (InsOrdHashSet _ m) =
HashMap.keysSet m
-------------------------------------------------------------------------------
-- Internal
-------------------------------------------------------------------------------
fromHashMapInt :: HashMap k Int -> InsOrdHashSet k
fromHashMapInt = mk . flip runState 0 . traverseWithKeyOrderedBy id (\_ _ -> newInt')
where
mk (m, i) = InsOrdHashSet i m
newInt' :: State Int Int
newInt' = state $ \s -> (s, s + 1)
-------------------------------------------------------------------------------
-- Valid
-------------------------------------------------------------------------------
-- | Test if the internal map structure is valid.
valid :: InsOrdHashSet a -> Bool
valid (InsOrdHashSet i m) = indexesDistinct && indexesSmaller
where
indexes :: [Int]
indexes = HashMap.elems m
indexesDistinct = indexes == nub indexes
indexesSmaller = all (< i) indexes