Implement Mut.restream
[darcs-mirrors/vector.git] / Data / Vector / MVector / Mut.hs
1 {-# LANGUAGE Rank2Types, ScopedTypeVariables #-}
2
3 #include "phases.h"
4
5 module Data.Vector.MVector.Mut (
6 Mut(..), run, unstream, update, reverse, map
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 Control.Monad ( liftM )
16 import Prelude hiding ( reverse, map )
17
18 data Mut a = Mut (forall m mv. MVector mv m a => m (mv a))
19
20 run :: MVector mv m a => Mut a -> m (mv a)
21 {-# INLINE run #-}
22 run (Mut p) = p
23
24 trans :: Mut a -> (forall m mv. MVector mv m a => mv a -> m ()) -> Mut a
25 {-# INLINE trans #-}
26 trans (Mut p) q = Mut (do { v <- p; q v; return v })
27
28 unstream :: Stream a -> Mut a
29 {-# INLINE_STREAM unstream #-}
30 unstream s = Mut (MVector.unstream s)
31
32 restream :: (forall m. Monad m => Stream (m a) -> Stream (m a))
33 -> Mut a -> Mut a
34 {-# INLINE_STREAM restream #-}
35 restream f (Mut p) = Mut (
36 do
37 v <- p
38 MVector.munstream v (f (MVector.mstream v)))
39
40 {-# RULES
41
42 "restream/restream [Mut]"
43 forall (f :: forall m. Monad m => Stream (m a) -> Stream (m a))
44 (g :: forall m. Monad m => Stream (m a) -> Stream (m a)) p .
45 restream f (restream g p) = restream (f . g) p
46
47 #-}
48
49 update :: Mut a -> Stream (Int, a) -> Mut a
50 {-# INLINE_STREAM update #-}
51 update m s = trans m (\v -> MVector.update v s)
52
53 reverse :: Mut a -> Mut a
54 {-# INLINE_STREAM reverse #-}
55 reverse m = trans m (MVector.reverse)
56
57 map :: (a -> a) -> Mut a -> Mut a
58 {-# INLINE map #-}
59 map f = restream (Stream.map (liftM f))
60