MVector.Mut -> MVector.New
[darcs-mirrors/vector.git] / Data / Vector / MVector / New.hs
1 {-# LANGUAGE Rank2Types, ScopedTypeVariables #-}
2
3 #include "phases.h"
4
5 module Data.Vector.MVector.New (
6 New(..), run, unstream, inplace, update, reverse, map, filter
7 ) where
8
9 import qualified Data.Vector.MVector as MVector
10 import Data.Vector.MVector ( MVector )
11
12 import Data.Vector.Stream ( Stream )
13 import qualified Data.Vector.Stream as Stream
14
15 import Data.Vector.MStream ( MStream )
16 import qualified Data.Vector.MStream as MStream
17
18 import Control.Monad ( liftM )
19 import Prelude hiding ( reverse, map, filter )
20
21 data New a = New (forall m mv. MVector mv m a => m (mv a))
22
23 run :: MVector mv m a => New a -> m (mv a)
24 {-# INLINE run #-}
25 run (New p) = p
26
27 modify :: New a -> (forall m mv. MVector mv m a => mv a -> m ()) -> New a
28 {-# INLINE modify #-}
29 modify (New p) q = New (do { v <- p; q v; return v })
30
31 unstream :: Stream a -> New a
32 {-# INLINE_STREAM unstream #-}
33 unstream s = New (MVector.unstream s)
34
35 inplace :: (forall m. Monad m => MStream m a -> MStream m a) -> New a -> New a
36 {-# INLINE_STREAM inplace #-}
37 inplace f (New p) = New (
38 do
39 v <- p
40 MVector.munstream v (f (MVector.mstream v)))
41
42 {-# RULES
43
44 "inplace/inplace [New]"
45 forall (f :: forall m. Monad m => MStream m a -> MStream m a)
46 (g :: forall m. Monad m => MStream m a -> MStream m a) p .
47 inplace f (inplace g p) = inplace (f . g) p
48
49 #-}
50
51 update :: New a -> Stream (Int, a) -> New a
52 {-# INLINE_STREAM update #-}
53 update m s = modify m (\v -> MVector.update v s)
54
55 reverse :: New a -> New a
56 {-# INLINE_STREAM reverse #-}
57 reverse m = modify m (MVector.reverse)
58
59 map :: (a -> a) -> New a -> New a
60 {-# INLINE map #-}
61 map f = inplace (MStream.map f)
62
63 filter :: (a -> Bool) -> New a -> New a
64 {-# INLINE filter #-}
65 filter f = inplace (MStream.filter f)
66