packages feed

pykinos-containers-0.1.1.0: src/Pykinos/Containers/IntMap/Strict.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DerivingStrategies #-}
-- | Module: Pykinos.Containers.IntMap.Strict
-- Description: Drop-in Data.IntMap.Strict façade backed by Adaptive Radix Trees (ART)
--
-- Drop-in replacement for @Data.IntMap.Strict@ backed by cache-efficient 4-tier
-- Adaptive Radix Trees ('ARTIntMap').
--
-- = Architectural Mechanics
--
-- * Bounded tree depth: At most 8 pointer hops on 64-bit platforms, with single-child
--   paths compressed into prefix slices ('ARTLeaf' / 'pref').
-- * Adaptive node fanout: Dynamically transitions across 4 node layouts (4, 16, 48,
--   and 256 children) to balance span density and memory footprint.
-- * Lawful instances: 'Functor', 'Foldable', and 'Traversable' satisfy all categorical
--   laws and require no typeclass constraints on value transformations.
module Pykinos.Containers.IntMap.Strict
  ( -- * IntMap Type
    IntMap(..)
    -- * Construction
  , empty
  , singleton
  , fromList
  , fromListWith
    -- * Queries
  , null
  , size
  , member
  , notMember
  , lookup
  , findWithDefault
    -- * Modifications
  , insert
  , insertWith
  , delete
    -- * Combinators
  , union
  , unionWith
  , intersection
  , intersectionWith
  , difference
    -- * Conversions & Projections
  , toAscList
  , toList
  , keys
  , elems
  , keysSet
  ) where

import Prelude hiding (lookup, null)
import Control.DeepSeq (NFData(..))
import Data.List (sortOn)
import Data.Maybe (fromMaybe)
import qualified Pykinos.Containers.IntSet as IS
import Pykinos.IntMap.ART
  ( ARTIntMap(..)
  , artDelete
  , artFromList
  , artInsert
  , artInsertWith
  , artKeysSet
  , artLookup
  , artMember
  , artToList
  , emptyART
  , singletonART
  )

-- | Strict integer-keyed map backed by an Adaptive Radix Tree.
newtype IntMap a = IntMap { unIntMap :: ARTIntMap a }
  deriving stock (Functor, Foldable, Traversable)

instance Eq a => Eq (IntMap a) where
  m1 == m2 = toAscList m1 == toAscList m2
  {-# INLINE (==) #-}

instance Show a => Show (IntMap a) where
  showsPrec p m = showParen (p > 10) $
    showString "fromList " . showsPrec 11 (toAscList m)

instance Semigroup (IntMap a) where
  (<>) = union
  {-# INLINE (<>) #-}

instance Monoid (IntMap a) where
  mempty = empty
  {-# INLINE mempty #-}

instance NFData a => NFData (IntMap a) where
  rnf (IntMap m) = rnf (artToList m)
  {-# INLINE rnf #-}

-- | Construct the empty integer map.
--
-- Running time: \(O(1)\).
empty :: IntMap a
empty = IntMap emptyART
{-# INLINE empty #-}

-- | Construct a map containing a single key-value association.
--
-- Running time: \(O(1)\).
singleton :: Int -> a -> IntMap a
singleton k !v = IntMap (singletonART k v)
{-# INLINE singleton #-}

-- | Test whether the map is empty.
--
-- Running time: \(O(1)\).
null :: IntMap a -> Bool
null (IntMap ARTEmpty) = True
null _                 = False
{-# INLINE null #-}

-- | Number of associations in the map.
--
-- Running time: \(O(N)\).
size :: IntMap a -> Int
size = length . toAscList
{-# INLINE size #-}

-- | Test whether a key is present in the map.
--
-- Running time: \(O(\min(K, 8))\).
member :: Int -> IntMap a -> Bool
member k = artMember k . unIntMap
{-# INLINE member #-}

-- | Test whether a key is absent from the map.
notMember :: Int -> IntMap a -> Bool
notMember k m = not (member k m)
{-# INLINE notMember #-}

-- | Lookup the value associated with a key.
--
-- Running time: \(O(\min(K, 8))\).
lookup :: Int -> IntMap a -> Maybe a
lookup k = artLookup k . unIntMap
{-# INLINE lookup #-}

-- | Lookup with fallback default value.
findWithDefault :: a -> Int -> IntMap a -> a
findWithDefault def k m = fromMaybe def (lookup k m)
{-# INLINE findWithDefault #-}

-- | Insert a key-value pair, overwriting any existing binding.
insert :: Int -> a -> IntMap a -> IntMap a
insert k !v = IntMap . artInsert k v . unIntMap
{-# INLINE insert #-}

-- | Insert with combining function: @insertWith f key new_val map@.
insertWith :: (a -> a -> a) -> Int -> a -> IntMap a -> IntMap a
insertWith f k !v = IntMap . artInsertWith f k v . unIntMap
{-# INLINE insertWith #-}

-- | Delete a key from the map.
delete :: Int -> IntMap a -> IntMap a
delete k = IntMap . artDelete k . unIntMap
{-# INLINE delete #-}

-- | Left-biased union of two integer maps.
union :: IntMap a -> IntMap a -> IntMap a
union = unionWith const
{-# INLINE union #-}

-- | Union with combining function: @unionWith f m1 m2@.
-- In case of key collisions, combines the values with @f v1 v2@ where
-- @v1@ is from @m1@ and @v2@ is from @m2@.
unionWith :: (a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
unionWith f m1 m2 =
  foldl' (\acc (k, v2) -> insertWith (flip f) k v2 acc) m1 (toAscList m2)
{-# INLINE unionWith #-}

-- | Intersection of two integer maps, retaining values from the first map.
intersection :: IntMap a -> IntMap b -> IntMap a
intersection m1 m2 =
  fromList [ (k, v) | (k, v) <- toAscList m1, member k m2 ]
{-# INLINE intersection #-}

-- | Intersection with combining function.
intersectionWith :: (a -> b -> c) -> IntMap a -> IntMap b -> IntMap c
intersectionWith f m1 m2 =
  fromList [ (k, f v1 v2) | (k, v1) <- toAscList m1, Just v2 <- [lookup k m2] ]
{-# INLINE intersectionWith #-}

-- | Difference: remove all keys occurring in the second map.
difference :: IntMap a -> IntMap b -> IntMap a
difference m1 m2 =
  foldl' (\acc (k, _) -> delete k acc) m1 (toAscList m2)
{-# INLINE difference #-}

-- | Convert map associations to a list in ascending signed key order.
toAscList :: IntMap a -> [(Int, a)]
toAscList = sortOn fst . artToList . unIntMap
{-# INLINE toAscList #-}

-- | Alias for 'toAscList'.
toList :: IntMap a -> [(Int, a)]
toList = toAscList
{-# INLINE toList #-}

-- | List of all keys in ascending order.
keys :: IntMap a -> [Int]
keys = map fst . toAscList
{-# INLINE keys #-}

-- | List of all values in ascending key order.
elems :: IntMap a -> [a]
elems = map snd . toAscList
{-# INLINE elems #-}

-- | Extract all keys as a 'IS.IntSet' backed by a Roaring Bitmap.
keysSet :: IntMap a -> IS.IntSet
keysSet = IS.IntSet . artKeysSet . unIntMap
{-# INLINE keysSet #-}

-- | Construct a map from an association list.
fromList :: [(Int, a)] -> IntMap a
fromList = IntMap . artFromList
{-# INLINE fromList #-}

-- | Construct a map from an association list with a combining function.
fromListWith :: (a -> a -> a) -> [(Int, a)] -> IntMap a
fromListWith f = foldl' (\acc (k, v) -> insertWith f k v acc) empty
{-# INLINE fromListWith #-}