Make New a newtype
[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.Fusion.Stream ( Stream, MStream )
13 import qualified Data.Vector.Fusion.Stream as Stream
14
15 import qualified Data.Vector.Fusion.Stream.Monadic as MStream
16
17 import Control.Monad ( liftM )
18 import Prelude hiding ( reverse, map, filter )
19
20 newtype New a = New (forall m mv. MVector mv m a => m (mv a))
21
22 run :: MVector mv m a => New a -> m (mv a)
23 {-# INLINE run #-}
24 run (New p) = p
25
26 modify :: New a -> (forall m mv. MVector mv m a => mv a -> m ()) -> New a
27 {-# INLINE modify #-}
28 modify (New p) q = New (do { v <- p; q v; return v })
29
30 unstream :: Stream a -> New a
31 {-# INLINE_STREAM unstream #-}
32 unstream s = New (MVector.unstream s)
33
34 inplace :: (forall m. Monad m => MStream m a -> MStream m a) -> New a -> New a
35 {-# INLINE_STREAM inplace #-}
36 inplace f (New p) = New (
37 do
38 v <- p
39 MVector.munstream v (f (MVector.mstream v)))
40
41 {-# RULES
42
43 "inplace/inplace [New]"
44 forall (f :: forall m. Monad m => MStream m a -> MStream m a)
45 (g :: forall m. Monad m => MStream m a -> MStream m a)
46 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