代码之家  ›  专栏  ›  技术社区  ›  rampion

Haskell中的一种现有大小惰性向量类型

  •  36
  • rampion  · 技术社区  · 12 年前

    我希望能够使用O(1)分期寻址,向量类型根据所需索引缓慢增长。

    这可以通过使用配对 MVector (PrimState m) a : 用一个 PrimRef m [a] 使用非晶化O(1)存取的标准加倍算法来保持余数:

    {-# LANGUAGE ExistentialQuantification #-}
    module LazyVec where
    
    import Control.Monad.Primitive
    import Data.PrimRef
    import Data.Vector.Mutable (MVector)
    import qualified Data.Vector.Mutable as M
    import Data.Vector (fromList, thaw)
    import Control.Monad (forM_)
    
    data LazyVec m a = PrimMonad m => LazyVec (MVector (PrimState m) a) (PrimRef m [a])
    
    -- prime the LazyVec with the first n elements
    lazyFromListN :: PrimMonad m => Int -> [a] -> m (LazyVec m a)
    lazyFromListN n xs = do
      let (as,bs) = splitAt n xs
      mvec <- thaw $ fromList as
      mref <- newPrimRef bs
      return $ LazyVec mvec mref
    
    -- look up the i'th element
    lazyIndex :: PrimMonad m => Int -> LazyVec m a -> m a
    lazyIndex i lv@(LazyVec mvec mref) | i < 0     = error "negative index"
                                       | i < n     = M.read mvec i
                                       | otherwise = do
        xs <- readPrimRef mref
        if null xs
          then error "index out of range"
          else do
            -- expand the mvec by some power of 2
            -- so that it includes the i'th index
            -- or ends
            let n' = n * 2 ^ ( 1 +  floor (logBase 2 (toEnum (i `div` n))))
            let growth = n' - n
            let (as, bs) = splitAt growth xs
            M.grow mvec $ if null bs then length as else growth
            forM_ (zip [n,n+1..] as) . uncurry $ M.write mvec
            writePrimRef mref bs
            lazyIndex i lv
      where n = M.length mvec
    

    我可以使用我的代码,但我宁愿重用别人的代码(例如,我还没有测试过我的代码)。

    在某些包中是否存在具有这些语义的向量类型(从可能无限的列表中延迟创建,O(1)分摊访问)?

    1 回复  |  直到 11 年前
        1
  •  0
  •   Christian Conkle    11 年前

    正如Jake McArthur在评论中指出的:“如果它只是一个函数,那么我建议只使用一个现有的记忆包,比如 MemoTrie data-memocombinators 。他们应该让它变得容易。"

    推荐文章