Skip to content

Use "smart initialization" trick in more places #363

Closed
@sjakobi

Description

@sjakobi

#359 introduced a trick that replaces a write to an array by initializing the array with the same element. We can use the same trick in some more places:

  • insertNewKey.snocNewLeaf (refactor to use snoc #407):
    snocNewLeaf :: Leaf k v -> A.Array (Leaf k v) -> A.Array (Leaf k v)
    snocNewLeaf leaf ary = A.run $ do
    let n = A.length ary
    mary <- A.new_ (n + 1)
    A.copy ary 0 mary 0 n
    A.write mary n leaf
  • insertModifyingArr (refactor to use snoc #407) :
    insertModifyingArr :: Eq k => v -> (v -> (# v #)) -> k -> A.Array (Leaf k v)
    -> A.Array (Leaf k v)
    insertModifyingArr x f k0 ary0 = go k0 ary0 0 (A.length ary0)
    where
    go !k !ary !i !n
    | i >= n = A.run $ do
    -- Not found, append to the end.
    mary <- A.new_ (n + 1)
    A.copy ary 0 mary 0 n
    A.write mary n (L k x)
    return mary
    | otherwise = case A.index ary i of
    (L kx y) | k == kx -> case f y of
    (# y' #) -> if ptrEq y y'
    then ary
    else A.update ary i (L k y')
    | otherwise -> go k ary (i+1) n
    {-# INLINE insertModifyingArr #-}
  • updateOrSnocWithKey (refactor to use snoc #407) :
    updateOrSnocWithKey :: Eq k => (k -> v -> v -> (# v #)) -> k -> v -> A.Array (Leaf k v)
    -> A.Array (Leaf k v)
    updateOrSnocWithKey f k0 v0 ary0 = go k0 v0 ary0 0 (A.length ary0)
    where
    go !k v !ary !i !n
    | i >= n = A.run $ do
    -- Not found, append to the end.
    mary <- A.new_ (n + 1)
    A.copy ary 0 mary 0 n
    A.write mary n (L k v)
    return mary
    | L kx y <- A.index ary i
    , k == kx
    , (# v2 #) <- f k v y
    = A.update ary i (L k v2)
    | otherwise
    = go k v ary (i+1) n
    {-# INLINABLE updateOrSnocWithKey #-}
  • Strict.updateOrSnocWithKey

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions