packages feed

insert-ordered-containers 0.2.1.0 → 0.4

raw patch · 6 files changed

Files

CHANGELOG.md view
@@ -1,3 +1,52 @@+- 0.4+    - Lens and Opticd support moved to separate packages,+    - Numerous bug fixes around maintaining ordering.+    - New Ord instances.+    - Performance improvements.+    - Strictness improvements.++- 0.3.0.1+    - Fix quadratic behavior in traverseWithKey/for++- 0.3.0+    - Fix ordering when decoding from JSON (with tests)+      https://github.com/erikd/insert-ordered-containers/issues/7+      This is a breaking change.+    - GHC-9.14.1 support++- 0.2.7+    - Support GHC-8.6.5...9.12.1+    - Haskell code modernisation++- 0.2.6+    - Support GHC-8.6.5...9.10.1++- 0.2.5.3+    - Support `aeson-2.2`+    - Make `Prelude` import explicit (safe guard against additions to `Prelude`).++- 0.2.5.2+    - Actually drop `semigroups` dependency+    - Update bounds++- 0.2.5.1+    - Drop unnecessary dependencies `semigroups`, `base-compat`+    - Update bounds++- 0.2.5+    - Add `NFData(/1/2)` instances++- 0.2.4+    - Add `indexed-traversable` instances+    - lens-5 and optics-0.4 support++- 0.2.3+    - Add support for indexed `optics`+    - Only support GHC-8.0+++- 0.2.2+    - Add `Data.HashSet.InsOrd`+ - 0.2.1.0     - Fix `Traversable`, `TraversableWithIndex`, `FoldableWithIndex` to traverse       in insertion order
insert-ordered-containers.cabal view
@@ -1,65 +1,85 @@-name:           insert-ordered-containers-version:        0.2.1.0-synopsis:       Associative containers retating insertion order for traversals.-description:    Associative containers retating insertion order for traversals.-category:       Web-homepage:       https://github.com/phadej/insert-ordered-containers#readme-bug-reports:    https://github.com/phadej/insert-ordered-containers/issues-author:         Oleg Grenrus <oleg.grenrus@iki.fi>-maintainer:     Oleg Grenrus <oleg.grenrus@iki.fi>-license:        BSD3-license-file:   LICENSE-tested-with:    GHC==7.6.3, GHC==7.8.4, GHC==7.10.3, GHC==8.0.1-build-type:     Simple-cabal-version:  >= 1.10+cabal-version:      2.2+name:               insert-ordered-containers+version:            0.4+synopsis:+  Associative containers retaining insertion order for traversals. +description:+  Associative containers retaining insertion order for traversals.+  .+  The implementation is based on `unordered-containers`.+  .+  Instances for the @lens@ and @optics@ type classes live in the+  companion packages @insert-ordered-containers-lens@ and+  @insert-ordered-containers-optics@.++category:           Web+homepage:           https://github.com/erikd/insert-ordered-containers#readme+bug-reports:        https://github.com/erikd/insert-ordered-containers/issues+author:             Oleg Grenrus <oleg.grenrus@iki.fi>+maintainer:         Erik de Castro Lopo <erikd@mega-nerd.com>, Oleg Grenrus <oleg.grenrus@iki.fi>+license:            BSD-3-Clause+license-file:       LICENSE+build-type:         Simple+tested-with:+  GHC ==8.6.5+   || ==8.8.4+   || ==8.10.7+   || ==9.0.2+   || ==9.2.8+   || ==9.4.8+   || ==9.6.7+   || ==9.8.4+   || ==9.10.3+   || ==9.12.2+   || ==9.14.1+ extra-source-files:-    CHANGELOG.md-    README.md+  CHANGELOG.md+  README.md  source-repository head-  type: git-  location: https://github.com/phadej/insert-ordered-containers+  type:     git+  location: https://github.com/erikd/insert-ordered-containers  library-  hs-source-dirs:-      src-  ghc-options: -Wall+  default-language: Haskell2010+  hs-source-dirs:   src+  ghc-options:      -Wall -Wunused-packages   build-depends:-      base                  >=4.6      && <4.10-    , aeson                 >=1.0.0.0  && <1.2-    , base-compat           >=0.6.0    && <0.10-    , hashable              >=1.2.3.3  && <1.4-    , lens                  >=4.7      && <4.16-    , semigroupoids         >=4.3      && <5.2-    , semigroups            >=0.16.2.2 && <0.19-    , text                  >=1.2.0.6  && <1.3-    , transformers          >=0.3.0.0  && <0.6-    , unordered-containers  >=0.2.7.0  && <0.3+    , aeson                 >=2.2.3.0  && <2.4+    , base                  >=4.12.0.0 && <4.23+    , containers            >=0.6.0.1+    , deepseq               >=1.4.4.0  && <1.6+    , hashable              >=1.4.7.0  && <1.6+    , indexed-traversable   >=0.1.4    && <0.2+    , semigroupoids         >=6.0.1    && <6.1+    , transformers          >=0.5.6.2  && <0.7+    , unordered-containers  >=0.2.20   && <0.3+   exposed-modules:-      Data.HashMap.Strict.InsOrd-  default-language: Haskell2010+    Data.HashMap.Strict.InsOrd+    Data.HashSet.InsOrd +  other-modules:    Data.HashMap.InsOrd.Internal+ test-suite ins-ord-containers-tests-  type: exitcode-stdio-1.0-  main-is: Tests.hs-  hs-source-dirs:-      test-  ghc-options: -Wall+  default-language: Haskell2010+  type:             exitcode-stdio-1.0+  main-is:          Tests.hs+  hs-source-dirs:   test+  ghc-options:      -Wall++  -- inherited from library   build-depends:-      base     , aeson+    , base     , base-compat+    , ghc-heap     , hashable-    , lens-    , semigroupoids-    , semigroups-    , text-    , transformers-    , unordered-containers-    , base+    , indexed-traversable     , insert-ordered-containers-    , tasty             >= 0.10.1.2 && <0.12-    , tasty-quickcheck  >= 0.8.3.2  && <0.9-    , QuickCheck        >=2.7.6     && <2.10-  default-language: Haskell2010+    , QuickCheck                 >=2.13.2   && <2.20+    , tasty                      >=0.10.1.2 && <1.6+    , tasty-quickcheck           >=0.8.3.2  && <0.12+    , unordered-containers
+ src/Data/HashMap/InsOrd/Internal.hs view
@@ -0,0 +1,60 @@+module Data.HashMap.InsOrd.Internal where++import Prelude hiding (filter, foldr, lookup, map, null)++import Control.Monad.ST (runST)+import Data.List        (sortBy)+import Data.Ord         (comparing)+import Data.STRef       (newSTRef, readSTRef, writeSTRef)++import           Data.HashMap.Strict (HashMap)+import qualified Data.HashMap.Lazy   as HashMapLazy+import qualified Data.HashMap.Strict as HashMap+import qualified Data.IntMap.Strict  as IntMap++-------------------------------------------------------------------------------+-- Ordered traversal+-------------------------------------------------------------------------------++-- | Traverse a 'HashMap', sequencing effects in ascending order of the given+-- index rather than in the map's internal order. The result has the same+-- keys as the input. The index must be distinct for every entry.+--+-- O(n log n): sort the entries by index and traverse that list, then look+-- each result up by its index. (This replaces an insertion-sorting free+-- applicative, which was O(n^2).)+traverseWithKeyOrderedBy+    :: Applicative f+    => (a -> Int) -> (k -> a -> f b) -> HashMap k a -> f (HashMap k b)+traverseWithKeyOrderedBy ix f m =+    refill <$> traverse g (sortBy (comparing fst) [(ix a, (k, a)) | (k, a) <- HashMap.toList m])+  where+    g (i, (k, a)) = (,) i <$> f k a++    -- Results come back in ascending index order. We reuse m's structure rather+    -- than rebuilding with 'fromList', since that would need 'Hashable k', which+    -- the 'Traversable' instance can't require.+    refill rs =+        let im = IntMap.fromDistinctAscList rs+        in HashMap.map (\a -> im IntMap.! ix a) m++-------------------------------------------------------------------------------+-- Numbering+-------------------------------------------------------------------------------++-- | Replace each value @a@ by @f i a@, where @i@ counts the entries from 0 in+-- the map's internal order. Also returns the number of entries. The new+-- values are evaluated to WHNF.+numberWith :: (Int -> a -> b) -> HashMap k a -> (Int, HashMap k b)+numberWith f m = runST $ do+    counter <- newSTRef 0+    -- Data.HashMap.Strict.traverseWithKey would evaluate the values too, but+    -- in ST it allocates twice as much as the lazy one with ($!):+    -- https://github.com/haskell-unordered-containers/unordered-containers/issues/608+    m' <- HashMapLazy.traverseWithKey (\_ a -> do+        i <- readSTRef counter+        writeSTRef counter $! i + 1+        return $! f i a) m+    n <- readSTRef counter+    return (n, m')+{-# INLINE numberWith #-}
src/Data/HashMap/Strict/InsOrd.hs view
@@ -1,5 +1,3 @@-{-# LANGUAGE CPP                   #-}-{-# LANGUAGE DeriveDataTypeable    #-} {-# LANGUAGE DeriveFoldable        #-} {-# LANGUAGE DeriveFunctor         #-} {-# LANGUAGE DeriveTraversable     #-}@@ -70,57 +68,68 @@     fromList,     toHashMap,     fromHashMap,-    -- * Lenses-    hashMap,-    unorderedTraversal,     -- * Debugging     valid,     ) where -#ifndef MIN_VERSION_aeson-#define MIN_VERSION_aeson(x,y,z) 0-#endif--import Prelude        ()-import Prelude.Compat hiding (filter, foldr, lookup, map, null)+import Prelude+       (Bool (..), Eq, Functor, Int, Maybe (..), Ord (compare), all, const,+       flip, fmap, fst, id, max, maybe, min, otherwise, return, seq, snd, uncurry,+       zipWith, ($), (&&), (+), (.), (<$>), (<), (==), (>), (>=), (>>=), (||)) -import           Control.Applicative             (Const (..), (<**>))-import           Control.Arrow                   (first, second)-import           Data.Aeson-import qualified Data.Aeson.Encoding             as E-import           Data.Data                       (Data, Typeable)-import qualified Data.Foldable                   as F-import           Data.Functor.Apply              (Apply (..))-import           Data.Functor.Bind               (Bind (..))-import           Data.Hashable                   (Hashable (..))-import           Data.List                       (nub, sortBy)-import           Data.Maybe                      (fromMaybe)-import           Data.Ord                        (comparing)-import           Data.Semigroup                  (Semigroup (..))-import           Text.ParserCombinators.ReadPrec (prec)-import           Text.Read                       (Lexeme (..), Read (..), lexP,-                                                  parens, readListPrecDefault)+import Control.Applicative             (Applicative, Const (..))+import Control.Arrow                   (first, second)+import Control.DeepSeq                 (NFData (..))+import Data.Data+       (Constr, Data (..), DataType, Fixity (Prefix), gcast1, gcast2, mkConstr,+       mkDataType)+import Data.Foldable                   (Foldable (foldMap))+import Data.Foldable.WithIndex         (FoldableWithIndex (..))+import Data.Functor.Apply              (Apply (..))+import Data.Functor.Bind               (Bind (..))+import Data.Functor.WithIndex          (FunctorWithIndex (..))+import Data.Hashable                   (Hashable (..))+import Data.List                       (nub, sortBy)+import Data.Maybe                      (fromMaybe)+import Data.Monoid                     (Monoid, mempty)+import Data.Ord                        (comparing)+import Data.Semigroup                  (Semigroup (..))+import Data.Traversable                (Traversable (traverse))+import Data.Traversable.WithIndex      (TraversableWithIndex (..))+import Text.ParserCombinators.ReadPrec (prec)+import Text.Read+       (Lexeme (..), Read (..), lexP, parens, readListPrecDefault)+import Text.Show                       (Show (..), showParen, showString) -import Control.Lens                     (At (..), FoldableWithIndex (..),-                                         FunctorWithIndex (..), Index, Iso, IxValue,-                                         Ixed (..), TraversableWithIndex (..),-                                         Traversal, iso, (<&>), _1, _2) import Control.Monad.Trans.State.Strict (State, runState, state) +import qualified Data.Aeson          as A+import qualified Data.Aeson.Types    as A+import qualified Data.Foldable       as F+ import           Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap -#if MIN_VERSION_base(4,7,0) import qualified GHC.Exts as Exts-#endif +import qualified Control.DeepSeq as NF++import Data.HashMap.InsOrd.Internal+ ------------------------------------------------------------------------------- -- Strict Pair Int a -------------------------------------------------------------------------------  data P a = P !Int !a-    deriving (Functor, Foldable, Traversable, Typeable, Data)+    deriving (Functor, Foldable, Traversable) +instance NFData a => NFData (P a) where+    rnf (P _ a) = rnf a++-- | @since 0.2.5+instance NF.NFData1 P where+    liftRnf rnf1 (P _ a) = rnf1 a+ getPK :: P a -> Int getPK (P i _) = i {-# INLINABLE getPK #-}@@ -129,6 +138,13 @@ getPV (P _ a) = a {-# INLINABLE getPV #-} +-- | Combiner for 'HashMap.fromListWith' over entries in ascending index+-- order: keep the position of the old (earlier) entry and the value of the+-- new (later) one.+keepIndex :: P a -> P a -> P a+keepIndex (P _ v) (P i _) = P i v+{-# INLINE keepIndex #-}+ incPK :: Int -> P a -> P a incPK i (P j x) = P (i + j) x {-# INLINABLE incPK #-}@@ -146,17 +162,56 @@ -- InsOrdHashMap ------------------------------------------------------------------------------- --- | 'HashMap' which tries it's best to remember insertion order of elements.-+-- | A 'HashMap' that keeps its entries in insertion order.+--+-- A new key is added at the end. Updating the value of an existing key keeps+-- its position. Deleting a key and inserting it again moves it to the end. data InsOrdHashMap k v = InsOrdHashMap     { _getIndex        :: !Int     , getInsOrdHashMap :: !(HashMap k (P v))     }-    deriving (Functor, Typeable, Data)+    deriving (Functor) +-- | Presented as a single virtual constructor @fromList@ applied to the+-- entries in insertion order.+instance (Data k, Data v, Eq k, Hashable k) => Data (InsOrdHashMap k v) where+    gfoldl f z m   = z fromList `f` toList m+    toConstr _     = fromListConstr+    gunfold k z _  = k (z fromList)+    dataTypeOf _   = insOrdHashMapDataType+    dataCast1 f    = gcast1 f+    dataCast2 f    = gcast2 f++fromListConstr :: Constr+fromListConstr = mkConstr insOrdHashMapDataType "fromList" [] Prefix++insOrdHashMapDataType :: DataType+insOrdHashMapDataType =+    mkDataType "Data.HashMap.Strict.InsOrd.InsOrdHashMap" [fromListConstr]++-- | @since 0.2.5+instance (NFData k, NFData v) => NFData (InsOrdHashMap k v) where+    rnf (InsOrdHashMap _ hm) = rnf hm++-- | @since 0.2.5+instance NFData k => NF.NFData1 (InsOrdHashMap k) where+    liftRnf rnf2 = NF.liftRnf2 rnf rnf2++-- | @since 0.2.5+instance NF.NFData2 InsOrdHashMap  where+    liftRnf2 rnf1 rnf2 (InsOrdHashMap _ m) = NF.liftRnf2 rnf1 (NF.liftRnf rnf2) m++-- | Equality is order sensitive: maps with the same entries in a different+-- insertion order are not equal. instance (Eq k, Eq v) => Eq (InsOrdHashMap k v) where-    InsOrdHashMap _ a == InsOrdHashMap _ b = a == b+    a == b = toList a == toList b +-- | Compares the entries lexicographically, in insertion order.+--+-- @since FIXME+instance (Ord k, Ord v) => Ord (InsOrdHashMap k v) where+    compare a b = compare (toList a) (toList b)+ instance (Show k, Show v) => Show (InsOrdHashMap k v) where     showsPrec d m = showParen (d > 10) $         showString "fromList " . showsPrec 11 (toList m)@@ -174,7 +229,6 @@  instance (Eq k, Hashable k) => Monoid (InsOrdHashMap k v) where     mempty = empty-    mappend = union  -- We cannot derive this, as we want to ordered folding and traversing instance Foldable (InsOrdHashMap k) where@@ -182,11 +236,9 @@     -- length = length . getInsOrdHashMap     foldMap f = foldMap (f . snd) . toList -#if MIN_VERSION_base(4,8,0)     null = null     toList = elems     length = size-#endif  instance Traversable (InsOrdHashMap k) where     traverse f m = traverseWithKey (\_ -> f) m@@ -204,72 +256,60 @@     hashWithSalt salt (InsOrdHashMap _ m) =         hashWithSalt salt m -#if MIN_VERSION_base(4,7,0) instance (Eq k, Hashable k) => Exts.IsList (InsOrdHashMap k v) where     type Item (InsOrdHashMap k v) = (k, v)     fromList = fromList     toList   = toList-#endif  ------------------------------------------------------------------------------- -- Aeson ------------------------------------------------------------------------------- -instance (ToJSONKey k) => ToJSON1 (InsOrdHashMap k) where-    liftToJSON t _ = case toJSONKey :: ToJSONKeyFunction k of-      ToJSONKeyText f _ -> object . fmap (\(k, v) -> (f k, t v)) . toList-      ToJSONKeyValue f _ -> toJSON . fmap (\(k,v) -> toJSON (f k, t v)) . toList+instance A.ToJSON2 InsOrdHashMap where+  liftToJSON2 omitKey encodeKey encodeKeyList omitVal encodeVal encodeValList =+    A.liftToJSON omitNothing encodeKVPair encodeKVPairList . toList+    where+      omitNothing _ = False+      encodeKVPair = A.liftToJSON2 omitKey encodeKey encodeKeyList omitVal encodeVal encodeValList+      encodeKVPairList = A.listValue encodeKVPair+  liftToEncoding2 omitKey encodeKey encodeKeyList omitVal encodeVal encodeValList =+    A.liftToEncoding omitNothing encodeKVPair encodeKVPairList . toList+    where+      omitNothing _ = False+      encodeKVPair = A.liftToEncoding2 omitKey encodeKey encodeKeyList omitVal encodeVal encodeValList+      encodeKVPairList = A.listEncoding encodeKVPair -    liftToEncoding t _ = case toJSONKey :: ToJSONKeyFunction k of-      ToJSONKeyText _ f ->  E.dict f t foldrWithKey-      ToJSONKeyValue _ f -> E.list (liftToEncoding2 f (E.list f) t (E.list t)) . toList+instance (A.ToJSON k) => A.ToJSON1 (InsOrdHashMap k) where+    liftToJSON = A.liftToJSON2 A.omitField A.toJSON A.toJSONList+    liftToEncoding = A.liftToEncoding2 A.omitField A.toEncoding A.toEncodingList -instance (ToJSONKey k, ToJSON v) => ToJSON (InsOrdHashMap k v) where-    toJSON = toJSON1-    toEncoding = toEncoding1+instance (A.ToJSON k, A.ToJSON v) => A.ToJSON (InsOrdHashMap k v) where+    toJSON = A.toJSON1+    toEncoding = A.toEncoding1  ------------------------------------------------------------------------------- -instance (Eq k, Hashable k, FromJSONKey k) => FromJSON1 (InsOrdHashMap k) where-    liftParseJSON p pl v = fromList . HashMap.toList <$> liftParseJSON p pl v+instance (Eq k, Hashable k, A.FromJSON k) => A.FromJSON1 (InsOrdHashMap k) where+    liftParseJSON o p pl v = fromList  <$> A.liftParseJSON Nothing pkv plkv v+      where+        pkv = A.liftParseJSON2 A.omittedField A.parseJSON A.parseJSONList o p pl+        plkv = A.listParser pkv -instance (Eq k, Hashable k, FromJSONKey k, FromJSON v) => FromJSON (InsOrdHashMap k v) where-    parseJSON = parseJSON1+instance (Eq k, Hashable k, A.FromJSON k, A.FromJSON v) => A.FromJSON (InsOrdHashMap k v) where+    parseJSON = A.parseJSON1  ---------------------------------------------------------------------------------- Lens+-- indexed-traversals ------------------------------------------------------------------------------- -type instance Index (InsOrdHashMap k v) = k-type instance IxValue (InsOrdHashMap k v) = v--instance (Eq k, Hashable k) => Ixed (InsOrdHashMap k v) where-    ix k f m = case lookup k m of-         Just v  -> f v <&> \v' -> insert k v' m-         Nothing -> pure m-    {-# INLINABLE ix #-}--instance (Eq k, Hashable k) => At (InsOrdHashMap k a) where-    at k f m = f mv <&> \r -> case r of-        Nothing -> maybe m (const (delete k m)) mv-        Just v' -> insert k v' m-      where mv = lookup k m-    {-# INLINABLE at #-}- instance (Eq k, Hashable k) => FunctorWithIndex k (InsOrdHashMap k) where     imap = mapWithKey instance (Eq k, Hashable k) => FoldableWithIndex k (InsOrdHashMap k) where     ifoldMap = foldMapWithKey+    ifoldr   = foldrWithKey instance (Eq k, Hashable k) => TraversableWithIndex k (InsOrdHashMap k) where     itraverse = traverseWithKey --- | This is a slight lie, as roundtrip doesn't preserve ordering.-hashMap :: Iso (InsOrdHashMap k a) (InsOrdHashMap k b) (HashMap k a) (HashMap k b)-hashMap = iso toHashMap fromHashMap--unorderedTraversal :: Traversal (InsOrdHashMap k a) (InsOrdHashMap k b) a b-unorderedTraversal = hashMap . traverse- ------------------------------------------------------------------------------- -- Construction -------------------------------------------------------------------------------@@ -352,33 +392,31 @@ -- Combine ------------------------------------------------------------------------------- --- | The union of two maps.  If a key occurs in both maps,--- the provided function (first argument) will be used to compute the result.------ Ordered traversal will go thru keys in the first map first.+-- | Like 'union', but if a key occurs in both maps, the given function+-- combines the two values. unionWith     :: (Eq k, Hashable k)     => (v -> v -> v)     -> InsOrdHashMap k v -> InsOrdHashMap k v -> InsOrdHashMap k v-unionWith f (InsOrdHashMap i a) (InsOrdHashMap j b) =-    mk $ HashMap.unionWith f' a b'-  where-    -- the threshold is arbitrary, it meant to amortise need for packing of indices-    mk | i > 0xfffff || j >= 0xfffff = fromHashMapP-       | otherwise                   = InsOrdHashMap (i + j)-    b' = fmap (incPK i) b-    f' (P ii x) (P _ y) = P ii (f x y)+unionWith f = unionWithKey (\_ -> f) +-- | Like 'unionWith', but the function also receives the key. unionWithKey     :: (Eq k, Hashable k)     => (k -> v -> v -> v)     -> InsOrdHashMap k v -> InsOrdHashMap k v -> InsOrdHashMap k v unionWithKey f (InsOrdHashMap i a) (InsOrdHashMap j b) =-    InsOrdHashMap (i + j) $ HashMap.unionWithKey f' a b'+    mk $ HashMap.unionWithKey f' a b'   where-    b' = fmap (incPK i) b+    -- the threshold is arbitrary, it meant to amortise need for packing of indices+    mk | i > 0xfffff || j >= 0xfffff = fromHashMapP+       | otherwise                   = InsOrdHashMap (i + j)+    b' = HashMap.map (incPK i) b     f' k (P ii x) (P _ y) = P ii (f k x y) +-- | The union of two maps: the entries of the first map in their order,+-- followed by the entries of the second map whose keys are not in the first,+-- in their order. union     :: (Eq k, Hashable k)     => InsOrdHashMap k v -> InsOrdHashMap k v -> InsOrdHashMap k v@@ -394,18 +432,49 @@ -------------------------------------------------------------------------------  -- | Order preserving mapping of keys.+--+-- If @f@ maps several keys to the same key, the result takes the position of+-- the earliest of them and the value of the latest, so+-- @mapKeys f = 'fromList' . fmap (first f) . 'toList'@. mapKeys :: (Eq k', Hashable k') => (k -> k') -> InsOrdHashMap k v -> InsOrdHashMap k' v mapKeys f (InsOrdHashMap i m) = InsOrdHashMap i $-    HashMap.fromList . fmap (first f) . HashMap.toList $ m+    mergeKeys . fmap (first f) . HashMap.toList $ m+{-# INLINABLE mapKeys #-} +-- | Order preserving traversal of keys.+--+-- The effects are performed in insertion order. Keys that @f@ maps to the+-- same key are merged as in 'mapKeys'. traverseKeys     :: (Eq k', Hashable k', Applicative f)     => (k -> f k') -> InsOrdHashMap k v -> f (InsOrdHashMap k' v)-traverseKeys f (InsOrdHashMap i m) = InsOrdHashMap i . HashMap.fromList <$>-    (traverse . _1) f (HashMap.toList m)+traverseKeys f (InsOrdHashMap i m) =+    -- The entries are traversed in ascending index order, so the cheaper+    -- 'keepIndex' suffices here instead of 'mergeKeys'.+    InsOrdHashMap i . HashMap.fromListWith keepIndex <$>+        traverse (\(k, p) -> (\k' -> (k', p)) <$> f k)+            (sortBy (comparing (getPK . snd)) (HashMap.toList m))+{-# INLINABLE traverseKeys #-} +-- | Build a map from entries, in any order, whose keys may have been merged.+-- A merged key takes the earliest position and the value of the latest entry.+--+-- While merging, each key carries its earliest position and its latest entry.+-- Keeping only a single 'P' would lose track of which position the value came+-- from, and the result would then depend on the order of the list. For a list+-- already in ascending index order, use 'keepIndex' instead.+mergeKeys :: (Eq k, Hashable k) => [(k, P v)] -> HashMap k (P v)+mergeKeys = HashMap.map finish . HashMap.fromListWith merge . fmap start+  where+    start (k, p) = (k, P (getPK p) p)++    merge (P a p) (P b q) = P (min a b) (if getPK p > getPK q then p else q)++    finish (P a (P _ v)) = P a v+{-# INLINABLE mergeKeys #-}+ map :: (v1 -> v2) -> InsOrdHashMap k v1 -> InsOrdHashMap k v2-map = fmap+map f (InsOrdHashMap i m) = InsOrdHashMap i $ HashMap.map (fmap f) m  mapWithKey :: (k -> v1 -> v2) -> InsOrdHashMap k v1 -> InsOrdHashMap k v2 mapWithKey f (InsOrdHashMap i m) =@@ -417,39 +486,8 @@ foldMapWithKey f = foldMap (uncurry f) . toList  traverseWithKey :: Applicative f => (k -> a -> f b) -> InsOrdHashMap k a -> f (InsOrdHashMap k b)-traverseWithKey f (InsOrdHashMap n m) = InsOrdHashMap n <$> retractSortedAp-    (HashMap.traverseWithKey (\k (P i v) -> liftSortedAp i (P i <$> f k v)) m)---- Sort using insertion sort--- Hopefully it's fast enough for where we need it--- otherwise: https://gist.github.com/treeowl/9621f58d55fe0c4f9162be0e074b1b29--- http://elvishjerricco.github.io/2017/03/23/applicative-sorting.html also related---- Free applicative which re-orders effects--- Mostly from Edward Kmett's `free` package.-data SortedAp f a where-    Pure :: a -> SortedAp f a-    SortedAp   :: !Int -> f a -> SortedAp f (a -> b) -> SortedAp f b--instance Functor (SortedAp f) where-    fmap f (Pure a)   = Pure (f a)-    fmap f (SortedAp i x y)   = SortedAp i x ((f .) <$> y)--instance Applicative (SortedAp f) where-    pure = Pure-    Pure f <*> y = fmap f y-    -- This is different from real Ap-    f <*> Pure y = fmap ($ y) f-    f@(SortedAp i x y) <*> z@(SortedAp j u v)-        | i < j     = SortedAp i x (flip <$> y <*> z)-        | otherwise = SortedAp j u ((.) <$> f <*> v)--liftSortedAp :: Int -> f a -> SortedAp f a-liftSortedAp i x = SortedAp i x (Pure id)--retractSortedAp :: Applicative f => SortedAp f a -> f a-retractSortedAp (Pure x) = pure x-retractSortedAp (SortedAp _ f x) = f <**> retractSortedAp x+traverseWithKey f (InsOrdHashMap n m) = InsOrdHashMap n <$>+    traverseWithKeyOrderedBy getPK (\k (P i v) -> P i <$> f k v) m  ------------------------------------------------------------------------------- -- Unordered@@ -466,8 +504,7 @@  -- | More efficient than 'traverse', when traversing in insertion order is not important. unorderedTraverse :: Applicative f => (a -> f b) -> InsOrdHashMap k a -> f (InsOrdHashMap k b)-unorderedTraverse f (InsOrdHashMap i m) =-    InsOrdHashMap i <$> (traverse . traverse) f m+unorderedTraverse f = unorderedTraverseWithKey (\_ -> f)  -- | More efficient than `traverseWithKey`, when traversing in insertion order is not important. unorderedTraverseWithKey :: Applicative f => (k -> a -> f b) -> InsOrdHashMap k a -> f (InsOrdHashMap k b)@@ -486,17 +523,22 @@ difference (InsOrdHashMap i a) (InsOrdHashMap _ b) =     InsOrdHashMap i $ HashMap.difference a b +-- | The intersection of two maps: the entries of the first map whose keys+-- are also in the second map, in the order of the first map. intersection     :: (Eq k, Hashable k)     => InsOrdHashMap k v -> InsOrdHashMap k w -> InsOrdHashMap k v intersection = intersectionWith const +-- | Like 'intersection', but combines the values of both maps with the given+-- function. intersectionWith     :: (Eq k, Hashable k)     => (v1 -> v2 -> v3)     -> InsOrdHashMap k v1 -> InsOrdHashMap k v2 -> InsOrdHashMap k v3 intersectionWith f = intersectionWithKey (\_ -> f) +-- | Like 'intersectionWith', but the function also receives the key. intersectionWithKey     :: (Eq k, Hashable k)     => (k -> v1 -> v2 -> v3)@@ -567,15 +609,24 @@ elems = fmap snd . toList {-# INLINABLE elems #-} -fromList :: forall k v. (Eq k, Hashable k) => [(k, v)] -> InsOrdHashMap k v-fromList-    = mk-    . flip runState 0-    . (traverse . _2) newP+-- | Construct a map from a list of key-value pairs.+--+-- If a key occurs more than once, it keeps the position of its first+-- occurrence and the value of its last.+--+-- >>> fromList [(1, 'a'), (2, 'b'), (1, 'c')]+-- fromList [(1,'c'),(2,'b')]+fromList :: (Eq k, Hashable k) => [(k, v)] -> InsOrdHashMap k v+fromList xs = InsOrdHashMap counter m   where-    mk :: ([(k, P v)], Int) -> InsOrdHashMap k v-    mk (m, i) = InsOrdHashMap i (HashMap.fromList m)+    m = HashMap.fromListWith keepIndex (zipWith indexed [0 ..] xs) +    -- Forcing the P here avoids handing a thunk to fromListWith.+    indexed i (k, v) = let p = P i v in p `seq` (k, p)++    counter = HashMap.foldl' (\i (P j _) -> max i (j + 1)) 0 m+{-# INLINABLE fromList #-}+ toList :: InsOrdHashMap k v -> [(k, v)] toList     = fmap (second getPV)@@ -590,27 +641,25 @@     . HashMap.toList     . getInsOrdHashMap +-- | Convert a 'HashMap'. The insertion order of the result is the order of+-- 'HashMap.toList', which is unspecified.+--+-- The values are evaluated to WHNF. fromHashMap :: HashMap k v -> InsOrdHashMap k v-fromHashMap = mk . flip runState 0 . traverse newP-  where-    mk (m, i) = InsOrdHashMap i m+fromHashMap m = case numberWith P m of+    (n, m') -> InsOrdHashMap n m'  toHashMap :: InsOrdHashMap k v -> HashMap k v-toHashMap (InsOrdHashMap _ m) = fmap getPV m+toHashMap (InsOrdHashMap _ m) = HashMap.map getPV m  ------------------------------------------------------------------------------- -- Internal ------------------------------------------------------------------------------- --- TODO: more efficient way is to do two traversals--- - collect the indexes--- - pack the indexes (Map old new)--- - traverse second time, changing the indexes fromHashMapP :: HashMap k (P v) -> InsOrdHashMap k v-fromHashMapP = mk . flip runState 0 . retractSortedAp . traverse f+fromHashMapP = mk . flip runState 0 . traverseWithKeyOrderedBy getPK (\_ (P _ v) -> newP v)   where     mk (m, i) = InsOrdHashMap i m-    f (P i v) = liftSortedAp i (newP v)  -- | Test if the internal map structure is valid. valid :: InsOrdHashMap k v -> Bool
+ src/Data/HashSet/InsOrd.hs view
@@ -0,0 +1,327 @@+{-# 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
test/Tests.hs view
@@ -3,18 +3,28 @@ import Prelude        () import Prelude.Compat -import Control.Lens   (folded, ifolded, (^..), (^@..))-import Data.Function  (on)-import Data.Hashable  (Hashable (..))-import Data.List      (nubBy)-import Data.Semigroup ((<>))-import Data.Traversable (foldMapDefault)-import Data.Word      (Word8)-import Text.Read      (readMaybe)+import Control.Exception       (ErrorCall (..), evaluate, try)+import Data.Bifunctor          (first)+import Data.Data               (Data, cast, gmapT)+import Data.Functor.Identity   (Identity (..))+import Data.Foldable.WithIndex (ifoldr, itoList)+import Data.Hashable           (Hashable (..))+import Data.List               (nub)+import Data.Maybe              (fromMaybe)+import Data.Traversable        (foldMapDefault)+import Data.Word               (Word8)+import GHC.Exts.Heap+       (GenClosure (..), allClosures, asBox, getBoxedClosureData)+import System.Mem              (performMajorGC)+import Text.Read               (readMaybe)  import qualified Data.Aeson                 as Aeson+import qualified Data.HashMap.Lazy          as HashMapLazy import qualified Data.HashMap.Strict        as HashMap import qualified Data.HashMap.Strict.InsOrd as InsOrd+import qualified Data.HashSet               as HashSet+import qualified Data.HashSet.InsOrd        as InsOrdSet+import qualified Data.List                  as List  import Test.QuickCheck.Function import Test.Tasty@@ -23,27 +33,166 @@ main :: IO () main = defaultMain $ testGroup "tests"     [ testGroup "Properties" $-        [ testProperty "toList . fromList ~= id" $ toListFromList+        [ testProperty "fromList keeps keys in order of first occurrence" $ fromListKeys+        , testProperty "fromList keeps the last value of each key" $ fromListValues+        , testProperty "fromList agrees with repeated insert" $ fromListInsert+        , testProperty "toHashMap . fromHashMap = id" $ fromHashMapRoundtrip+        , testProperty "fromHashMap keeps the order of HashMap.toList" $ fromHashMapOrder+        , testProperty "InsOrdHashSet toHashSet . fromHashSet = id" $ fromHashSetRoundtrip+        , testProperty "InsOrdHashSet fromHashSet keeps the order of HashSet.toList" $ fromHashSetOrder         , testProperty "toList distributes over mappend" $ toListMappendDistribute         , testProperty "behaves like HashMap" $ operationModel         , testProperty "valid" $ validProperty         , testProperty "Hashable agree" $ hashableProperty         , testProperty "aeson roundtrip" $ aesonRoundtrip         , testProperty "show . read = id" showReadRoundtrip+        , testProperty "Eq respects ordering" eqRespectsOrdering+        , testProperty "Ord compares entries in insertion order" ordMap+        , testProperty "InsOrdHashSet Ord compares elements in insertion order" ordSet+        , testProperty "traverseWithKey effects in insertion order" traverseWithKeyOrder+        , testProperty "InsOrdHashSet fromList keeps elements in order of first occurrence" $ setFromListOrder+        , testProperty "InsOrdHashSet fromList agrees with repeated insert" $ setFromListInsert         ]+    , testGroup "Key-merging transformations (issue 34)"+        [ testProperty "InsOrdHashSet map = fromList . fmap f . toList" setMapMerge+        , testProperty "mapKeys = fromList . fmap (first f) . toList" mapKeysMerge+        , testProperty "traverseKeys = fromList . fmap (first f) . toList" traverseKeysMerge+        , testProperty "traverseKeys effects in insertion order" traverseKeysOrder+        , testProperty "issue 34 InsOrdHashSet map example" issue34Set+        , testProperty "issue 34 mapKeys example" issue34MapKeys+        , testProperty "issue 34 traverseKeys example" issue34TraverseKeys+        ]+    , testGroup "Value strictness"+        [ testProperty "map" $ mapStrict+        , testProperty "unorderedTraverse" $ unorderedTraverseStrict+        , testProperty "fromHashMap" $ fromHashMapStrict+        ]+    , testGroup "No thunks stored"+        [ testProperty "InsOrdHashMap operations" $ opNoThunks+        , testProperty "unionWith" $ unionWithNoThunks+        , testProperty "toHashMap" $ toHashMapNoThunks+        , testProperty "InsOrdHashSet union" $ setUnionNoThunks+        ]     , testGroup "Regressions"         [ testProperty "issue 10: union overflow" $ issue10+        , testProperty "issue 10: unionWithKey overflow" $ issue10WithKey         , testProperty "issue 12 Foldable" $ issue12a         , testProperty "issue 12 Traversable" $ issue12b-        , testProperty "issue 12 FoldableWithIndex ^.." $ issue12c-        , testProperty "issue 12 FoldableWithIndex ^@.." $ issue12d+        , testProperty "issue 12 FoldableWithIndex ifoldr" $ issue12c+        , testProperty "issue 12 FoldableWithIndex itoList" $ issue12d+        , testProperty "issue 19 Data InsOrdHashMap" $ issue19Map+        , testProperty "issue 19 Data InsOrdHashSet" $ issue19Set+        , testProperty "issue 19 Data InsOrdHashMap identity" $ issue19MapIdentity+        , testProperty "issue 19 Data InsOrdHashSet identity" $ issue19SetIdentity+        , testProperty "issue 27 InsOrdHashSet Eq/Hashable ignore indices" $ issue27+        , testProperty "InsOrdHashSet union is valid and ordered" $ setUnion         ]     ] -toListFromList :: [(Int, Int)] -> Property-toListFromList l = l' === InsOrd.toList (InsOrd.fromList l)-  where l' = reverse . nubBy (on (==) fst) .  reverse $ l+fromListKeys :: [(Word8, Int)] -> Property+fromListKeys l = InsOrd.keys (InsOrd.fromList l) === nub (map fst l) +fromListValues :: [(Word8, Int)] -> Property+fromListValues l = InsOrd.toHashMap (InsOrd.fromList l) === HashMap.fromList l++fromListInsert :: [(Word8, Int)] -> Property+fromListInsert l = InsOrd.fromList l === List.foldl' (\m (k, v) -> InsOrd.insert k v m) InsOrd.empty l++fromHashMapRoundtrip :: [(Word8, Int)] -> Property+fromHashMapRoundtrip l =+    InsOrd.toHashMap iom === m .&&. property (InsOrd.valid iom)+  where+    m = HashMap.fromList l+    iom = InsOrd.fromHashMap m++fromHashMapOrder :: [(Int, Int)] -> Property+fromHashMapOrder l = InsOrd.toList (InsOrd.fromHashMap m) === HashMap.toList m+  where+    m = HashMap.fromList l++fromHashSetRoundtrip :: [Word8] -> Property+fromHashSetRoundtrip l =+    InsOrdSet.toHashSet ios === s .&&. property (InsOrdSet.valid ios)+  where+    s = HashSet.fromList l+    ios = InsOrdSet.fromHashSet s++fromHashSetOrder :: [Int] -> Property+fromHashSetOrder l = InsOrdSet.toList (InsOrdSet.fromHashSet s) === HashSet.toList s+  where+    s = HashSet.fromList l++setFromListOrder :: [Word8] -> Property+setFromListOrder l =+    InsOrdSet.toList s === nub l .&&. property (InsOrdSet.valid s)+  where+    s = InsOrdSet.fromList l++setFromListInsert :: [Word8] -> Property+setFromListInsert l =+    InsOrdSet.toList s === nub l+    .&&. property (InsOrdSet.valid s)+    .&&. s === InsOrdSet.fromList l+  where+    s = List.foldl' (flip InsOrdSet.insert) InsOrdSet.empty l++-- A function that merges many inputs, so that collisions are common.+merge :: Word8 -> Word8+merge = (`div` 16)++setMapMerge :: [Word8] -> Property+setMapMerge l =+    InsOrdSet.toList s' === InsOrdSet.toList (InsOrdSet.fromList (map merge (InsOrdSet.toList s)))+    .&&. property (InsOrdSet.valid s')+  where+    s  = InsOrdSet.fromList l+    s' = InsOrdSet.map merge s++mapKeysMerge :: [(Word8, Int)] -> Property+mapKeysMerge l =+    InsOrd.toList m' === InsOrd.toList (InsOrd.fromList (map (first merge) (InsOrd.toList m)))+    .&&. property (InsOrd.valid m')+  where+    m  = InsOrd.fromList l+    m' = InsOrd.mapKeys merge m++traverseKeysMerge :: [(Word8, Int)] -> Property+traverseKeysMerge l =+    InsOrd.toList m' === InsOrd.toList (InsOrd.fromList (map (first merge) (InsOrd.toList m)))+    .&&. property (InsOrd.valid m')+  where+    m  = InsOrd.fromList l+    m' = runIdentity (InsOrd.traverseKeys (Identity . merge) m)++traverseKeysOrder :: [(Word8, Int)] -> Property+traverseKeysOrder l = fst (InsOrd.traverseKeys (\k -> ([k], merge k)) m) === InsOrd.keys m+  where+    m = InsOrd.fromList l++issue34Set :: Property+issue34Set = InsOrdSet.toList (InsOrdSet.map f a) === [1, 0]+    .&&. InsOrdSet.toList (InsOrdSet.map f b) === [1, 0]+  where+    f = (`mod` 2) :: Int -> Int+    a = InsOrdSet.fromList [1, 2, 3]+    b = InsOrdSet.fromList [3, 2, 1]++issue34MapKeys :: Property+issue34MapKeys = InsOrd.toList (InsOrd.mapKeys f a) === [(1, 'z'), (0, 'y')]+    .&&. InsOrd.toList (InsOrd.mapKeys f b) === [(1, 'z'), (0, 'y')]+  where+    f = (`mod` 2) :: Int -> Int+    a = InsOrd.fromList [(1, 'x'), (2, 'y'), (3, 'z')]+    b = InsOrd.fromList [(3, 'x'), (2, 'y'), (1, 'z')]++issue34TraverseKeys :: Property+issue34TraverseKeys = go a === ([1, 2, 3], [(1, 'z'), (0, 'y')])+    .&&. go b === ([3, 2, 1], [(1, 'z'), (0, 'y')])+  where+    go = fmap InsOrd.toList . InsOrd.traverseKeys (\k -> ([k], k `mod` 2 :: Int))+    a = InsOrd.fromList [(1, 'x'), (2, 'y'), (3, 'z')]+    b = InsOrd.fromList [(3, 'x'), (2, 'y'), (1, 'z')]+ toListMappendDistribute :: [(Int, Int)] -> [(Int, Int)] -> Property toListMappendDistribute a b = rhs === lhs   where@@ -150,12 +299,117 @@     rhs = Just iom     lhs = readMaybe $ show iom ++eqRespectsOrdering :: Operation Int Int -> Property+eqRespectsOrdering op = iom == iomRev ==> InsOrd.toList iom === InsOrd.toList iomRev+  where+    iom = evalOpInsOrd op+    iomRev = InsOrd.fromList . reverse . InsOrd.toList $ iom++ordMap :: Operation Word8 Word8 -> Operation Word8 Word8 -> Property+ordMap opA opB =+    compare a b === compare (InsOrd.toList a) (InsOrd.toList b)+    .&&. (compare a b == EQ) === (a == b)+  where+    a = evalOpInsOrd opA+    b = evalOpInsOrd opB++ordSet :: [Word8] -> [Word8] -> Property+ordSet xs ys =+    compare a b === compare (InsOrdSet.toList a) (InsOrdSet.toList b)+    .&&. (compare a b == EQ) === (a == b)+  where+    a = InsOrdSet.fromList xs+    b = InsOrdSet.fromList ys++traverseWithKeyOrder :: Operation Word8 Int -> Property+traverseWithKeyOrder op =+    -- effects (which just accumulate key/value pairs here) ran in order:+    effects === InsOrd.toList iom+    .&&. InsOrd.toList iom' === [ (k, v + 1) | (k, v) <- InsOrd.toList iom ]+    .&&. property (InsOrd.valid iom')+  where+    iom = evalOpInsOrd op+    (effects, iom') = InsOrd.traverseWithKey (\k v -> ([(k, v)], v + 1)) iom+ -------------------------------------------------------------------------------+-- Value strictness+-------------------------------------------------------------------------------++-- | Evaluate the value to WHNF and check that no thunk is reachable from it.+--+-- Some thunks can't be detected with 'undefined', for example a thunk around+-- an already evaluated value, so this inspects the heap instead.+noThunks :: a -> Property+noThunks x = ioProperty $ do+    _ <- evaluate x+    -- Remove the indirections left behind by evaluated thunks.+    performMajorGC+    go (100000 :: Int) [asBox x]+  where+    go _ [] = return (property True)+    go 0 _  = return (counterexample "heap walk limit reached" False)+    go n (b : bs) = do+        c <- getBoxedClosureData b+        case c of+            ThunkClosure {}    -> found "THUNK"+            APClosure {}       -> found "AP"+            APStackClosure {}  -> found "AP_STACK"+            SelectorClosure {} -> found "THUNK_SELECTOR"+            BlackholeClosure { indirectee = b' } -> go (n - 1) (b' : bs)+            IndClosure { indirectee = b' }       -> go (n - 1) (b' : bs)+            _ -> go (n - 1) (allClosures c ++ bs)++    found kind = return (counterexample ("thunk found: " ++ kind) False)++opNoThunks :: Operation Word8 Int -> Property+opNoThunks op = noThunks (evalOpInsOrd op)++unionWithNoThunks :: [(Word8, Int)] -> [(Word8, Int)] -> Property+unionWithNoThunks a b = noThunks (InsOrd.unionWith (+) (InsOrd.fromList a) (InsOrd.fromList b))++toHashMapNoThunks :: Operation Word8 Int -> Property+toHashMapNoThunks op = noThunks (InsOrd.toHashMap (evalOpInsOrd op))++setUnionNoThunks :: [Word8] -> [Word8] -> Property+setUnionNoThunks a b = noThunks (InsOrdSet.union (InsOrdSet.fromList a) (InsOrdSet.fromList b))++-- | Evaluating the map to WHNF evaluates its values.+forcesValues :: InsOrd.InsOrdHashMap k v -> Property+forcesValues m = ioProperty $ do+    r <- try (evaluate m)+    return $ case r of+        Left (ErrorCall _) -> True+        Right _            -> False++mapStrict :: NonEmptyList (Word8, Int) -> Property+mapStrict (NonEmpty l) =+    forcesValues (InsOrd.map (\_ -> undefined :: Int) (InsOrd.fromList l))++unorderedTraverseStrict :: NonEmptyList (Word8, Int) -> Property+unorderedTraverseStrict (NonEmpty l) = forcesValues $ runIdentity $+    InsOrd.unorderedTraverse (\_ -> Identity (undefined :: Int)) (InsOrd.fromList l)++fromHashMapStrict :: NonEmptyList Word8 -> Property+fromHashMapStrict (NonEmpty ks) = forcesValues $+    InsOrd.fromHashMap (HashMapLazy.fromList [(k, undefined :: Int) | k <- ks])++------------------------------------------------------------------------------- -- Regressions ------------------------------------------------------------------------------- +-- 'unionWithKey' did not get the index repacking added to 'unionWith' for+-- issue 10, so repeated unions overflowed the insertion stamps.+issue10WithKey :: Property+issue10WithKey = InsOrd.elems p === "wold!" .&&. property (InsOrd.valid p)+  where+    m, n, p :: InsOrd.InsOrdHashMap Char Char+    m = InsOrd.fromList  (zip "hello" "world")+    n = iterate (\x -> InsOrd.unionWithKey (\_ a _ -> a) x x) m !! 64+    p = InsOrd.insert '!' '!' n+ issue12a :: Property-issue12a = (m ^.. folded) === "wold"+issue12a = foldr (:) [] m === "wold"   where     m :: InsOrd.InsOrdHashMap Char Char     m = InsOrd.fromList  (zip "hello" "world")@@ -167,20 +421,95 @@     m = InsOrd.fromList  (zip "hello" "world")  issue12c :: Property-issue12c = (m ^.. ifolded) === "wold"+issue12c = ifoldr (\_ v acc -> v : acc) [] m === "wold"   where     m :: InsOrd.InsOrdHashMap Char Char     m = InsOrd.fromList  (zip "hello" "world")  issue12d :: Property-issue12d = (m ^@.. ifolded) === (zip "helo" "wold")+issue12d = itoList m === zip "helo" "wold"   where     m :: InsOrd.InsOrdHashMap Char Char     m = InsOrd.fromList  (zip "hello" "world")  +-- Apply @f@ to every 'Int' inside a value, bottom-up, like syb's+-- @everywhere (mkT f)@.+mapInts :: Data a => (Int -> Int) -> a -> a+mapInts f = go+  where+    go :: Data b => b -> b+    go x = atInt (gmapT go x)++    atInt :: Data b => b -> b+    atInt x = fromMaybe x (cast . f =<< cast x)++issue19Map :: [(Int, Int)] -> Property+issue19Map l = InsOrd.toList m' === expected .&&. property (InsOrd.valid m')+  where+    m = InsOrd.fromList l+    m' = mapInts negate m+    expected = [ (negate k, negate v) | (k, v) <- InsOrd.toList m ]++issue19Set :: [Int] -> Property+issue19Set l =+    InsOrdSet.toList s' === expected .&&. property (InsOrdSet.valid s')+  where+    s = InsOrdSet.fromList l+    s' = mapInts negate s+    expected = map negate (InsOrdSet.toList s)++-- An identity generic transformation must yield an equal container, even+-- when duplicate insertions or deletions have left gaps in the internal+-- insertion stamps.+issue19MapIdentity :: [(Int, Int)] -> [Int] -> Property+issue19MapIdentity l ds =+    m' === m .&&. hash m' === hash m .&&. property (InsOrd.valid m')+  where+    m = List.foldl' (flip InsOrd.delete) (InsOrd.fromList (l ++ l)) ds+    m' = gmapT id m++issue19SetIdentity :: [Int] -> [Int] -> Property+issue19SetIdentity l ds =+    s' === s .&&. hash s' === hash s .&&. property (InsOrdSet.valid s')+  where+    s = List.foldl' (flip InsOrdSet.delete) (InsOrdSet.fromList (l ++ l)) ds+    s' = gmapT id s++-- Sets with the same elements in the same order must be equal and hash+-- alike, regardless of how they were built; equality is order sensitive.+issue27 :: Int -> Property+issue27 salt =+    a === b+    .&&. a =/= InsOrdSet.fromList [3, 1]+    .&&. hashWithSalt salt a === hashWithSalt salt b+    .&&. hashWithSalt salt a === hashWithSalt salt (InsOrdSet.toHashSet a)+  where+    a, b :: InsOrdSet.InsOrdHashSet Int+    a = InsOrdSet.delete 2 (InsOrdSet.fromList [1, 2, 3])+    b = InsOrdSet.fromList [1, 3]++-- 'InsOrdHashSet.union' used to give the right-hand set's last element a+-- stamp equal to the counter, so the result was not 'valid' and a later+-- 'insert' could collide with it.+setUnion :: [Int] -> [Int] -> Int -> Property+setUnion xs ys z =+    InsOrdSet.toList u === expected+    .&&. property (InsOrdSet.valid u)+    .&&. property (InsOrdSet.valid u')+    .&&. InsOrdSet.toList u' === expected'+  where+    a = InsOrdSet.fromList xs+    b = InsOrdSet.fromList ys+    u = InsOrdSet.union a b+    u' = InsOrdSet.insert z u+    expected =+        InsOrdSet.toList a+        ++ [ y | y <- InsOrdSet.toList b, not (InsOrdSet.member y a) ]+    expected' = nub (expected ++ [z])+ issue10 :: Property-issue10 = (p ^.. folded) === "wold!" .&&. property (InsOrd.valid p)+issue10 = InsOrd.elems p === "wold!" .&&. property (InsOrd.valid p)   where     m, n, p :: InsOrd.InsOrdHashMap Char Char     m = InsOrd.fromList  (zip "hello" "world")