Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add indexing for immutable vectors

  • Loading branch information...
commit f71b7024a012844c0895433755368beef755a6e6 1 parent c7865b1
@Shimuuar authored
Showing with 12 additions and 13 deletions.
  1. +7 −0 Data/Vector/Fixed/Mutable.hs
  2. +5 −13 Data/Vector/Fixed/Unboxed.hs
View
7 Data/Vector/Fixed/Mutable.hs
@@ -13,6 +13,7 @@ module Data.Vector.Fixed.Mutable (
, write
-- * Immutable vectors
, IVector(..)
+ , (!)
, lengthI
, freeze
, thaw
@@ -63,6 +64,8 @@ class (MVector (Mutable v) a) => IVector v a where
-- | Convert immutable vector to mutable. Immutable vector must not
-- be used afterwards.
unsafeThaw :: PrimMonad m => v a -> m (Mutable v (PrimState m) a)
+ -- | Get element at specified index
+ unsafeIndex :: v a -> Int -> a
-- | Length of immutable vector
lengthI :: IVector v a => v a -> Int
@@ -71,6 +74,10 @@ lengthI = lengthM . cast
cast :: v a -> Mutable v () a
cast _ = undefined
+(!) :: IVector v a => v a -> Int -> a
+v ! i | i < 0 || i >= lengthI v = error "Data.Vector.Fixed.Mutable.!: index out of bounds"
+ | otherwise = unsafeIndex v i
+
-- | Safely convert mutable vector to immutable.
freeze :: (PrimMonad m, IVector v a) => Mutable v (PrimState m) a -> m (v a)
{-# INLINE freeze #-}
View
18 Data/Vector/Fixed/Unboxed.hs
@@ -65,11 +65,12 @@ instance (Arity n, Prim a) => MVector (MVec n) a where
{-# INLINE unsafeWrite #-}
instance (Arity n, Prim a) => IVector (Vec n) a where
- unsafeFreeze (MVec off v) = do { a <- unsafeFreezeByteArray v; return $! Vec off a }
- unsafeThaw (Vec off v) = do { a <- unsafeThawByteArray v; return $! MVec off a }
+ unsafeFreeze (MVec off v) = do { a <- unsafeFreezeByteArray v; return $! Vec off a }
+ unsafeThaw (Vec off v) = do { a <- unsafeThawByteArray v; return $! MVec off a }
+ unsafeIndex (Vec off v) i = indexByteArray v (off + i)
{-# INLINE unsafeFreeze #-}
{-# INLINE unsafeThaw #-}
-
+ {-# INLINE unsafeIndex #-}
type instance Dim (Vec n) = n
@@ -86,7 +87,7 @@ newtype T_idx n = T_idx Int
inspectVec :: forall n a b. (Arity n, Prim a) => Vec n a -> Fun n a b -> b
{-# INLINE inspectVec #-}
inspectVec v (Fun f)
- = apply (\(T_idx i) -> (index i v, T_idx (i+1)))
+ = apply (\(T_idx i) -> (unsafeIndex v i, T_idx (i+1)))
(T_idx 0 :: T_idx n)
f
@@ -122,12 +123,3 @@ alloc = T_new 0 $ newByteArray $! arity (undefined :: n) * sizeOf (undefined ::
instance (Arity n, Prim a, Show a) => Show (Vec n a) where
show = show . toList
-
-
-----------------------------------------------------------------
--- Helpers
-----------------------------------------------------------------
-
--- Low level indexing operation
-index :: Prim a => Int -> Vec n a -> a
-index n (Vec off arr) = indexByteArray arr (off + n)
Please sign in to comment.
Something went wrong with that request. Please try again.