Removed 'group' function, updated rotl and rotr to work for empty vectors
[matthijs/master-project/support/tfvec.git] / Data / Param / TFVec.hs
1 ------------------------------------------------------------------------------
2 -- |
3 -- Module       : Data.Param.TFVec
4 -- Copyright    : (c) 2009 Christiaan Baaij
5 -- Licence      : BSD-style (see the file LICENCE)
6 --
7 -- Maintainer   : christiaan.baaij@gmail.com
8 -- Stability    : experimental
9 -- Portability  : non-portable
10 --
11 -- 'TFVec': Fixed sized vectors. Vectors with numerically parameterized size,
12 --          using type-level numerals from 'tfp' library
13 --
14 ------------------------------------------------------------------------------
15
16 module Data.Param.TFVec
17   ( TFVec
18   , empty
19   , (+>)
20   , singleton
21   , vectorCPS
22   , vectorTH
23   , unsafeVector
24   , readTFVec
25   , length
26   , lengthT
27   , fromVector
28   , null
29   , (!)
30   , replace
31   , head
32   , last
33   , init
34   , tail
35   , take
36   , drop
37   , select
38   , (<+)
39   , (++)
40   , map
41   , zipWith
42   , foldl
43   , foldr
44   , zip
45   , unzip
46   , shiftl
47   , shiftr
48   , rotl
49   , rotr
50   , concat
51   , reverse
52   , iterate
53   , generate
54   , copy
55   , copyn
56   ) where
57     
58
59 import Types
60 import Types.Data.Num.Decimal.Literals.TH
61 import Data.RangedWord
62
63 import Data.Generics (Data, Typeable)
64 import qualified Prelude as P
65 import Prelude hiding (
66   null, length, head, tail, last, init, take, drop, (++), map, foldl, foldr,
67   zipWith, zip, unzip, concat, reverse, iterate )
68 import qualified Data.Foldable as DF (Foldable, foldr)
69 import qualified Data.Traversable as DT (Traversable(traverse))
70 import Language.Haskell.TH
71 import Language.Haskell.TH.Syntax (Lift(..))
72
73 newtype (NaturalT s) => TFVec s a = TFVec {unTFVec :: [a]}
74   deriving (Eq, Typeable)
75
76 deriving instance (NaturalT s, Typeable s, Data s, Typeable a, Data a) => Data (TFVec s a)
77
78 -- ==========================
79 -- = Constructing functions =
80 -- ==========================
81                                                   
82 empty :: TFVec D0 a
83 empty = TFVec []
84
85 (+>) :: a -> TFVec s a -> TFVec (Succ s) a
86 x +> (TFVec xs) = TFVec (x:xs)
87
88 infix 5 +>
89
90 singleton :: a -> TFVec D1 a
91 singleton x = x +> empty
92
93 vectorCPS :: [a] -> (forall s . NaturalT s => TFVec s a -> w) -> w
94 vectorCPS xs = unsafeVectorCPS (toInteger (P.length xs)) xs
95
96 vectorTH :: Lift a => [a] -> ExpQ
97 vectorTH xs = (vectorCPS xs) lift
98
99 unsafeVector :: NaturalT s => s -> [a] -> TFVec s a
100 unsafeVector l xs
101   | fromIntegerT l /= P.length xs =
102     error (show 'unsafeVector P.++ ": dynamic/static lenght mismatch")
103   | otherwise = TFVec xs
104
105 readTFVec :: (Read a, NaturalT s) => String -> TFVec s a
106 readTFVec = read
107
108 readTFVecCPS :: Read a => String -> (forall s . NaturalT s => TFVec s a -> w) -> w
109 readTFVecCPS str = unsafeVectorCPS (toInteger l) xs
110  where fName = show 'readTFVecCPS
111        (xs,l) = case [(xs,l) | (xs,l,rest) <- readTFVecList str,  
112                            ("","") <- lexTFVec rest] of
113                        [(xs,l)] -> (xs,l)
114                        []   -> error (fName P.++ ": no parse")
115                        _    -> error (fName P.++ ": ambiguous parse")
116         
117 -- =======================
118 -- = Observing functions =
119 -- =======================
120 length :: forall s a . NaturalT s => TFVec s a -> Int
121 length _ = fromIntegerT (undefined :: s)
122
123 lengthT :: NaturalT s => TFVec s a -> s
124 lengthT = undefined
125
126 fromVector :: NaturalT s => TFVec s a -> [a]
127 fromVector (TFVec xs) = xs
128
129 null :: TFVec D0 a -> Bool
130 null _ = True
131
132 (!) ::  ( PositiveT s
133         , NaturalT u
134         , (s :>: u) ~ True) => TFVec s a -> RangedWord u -> a
135 (TFVec xs) ! i = xs !! (fromInteger (toInteger i))
136
137 -- ==========================
138 -- = Transforming functions =
139 -- ==========================
140 replace :: (PositiveT s, NaturalT u, (s :>: u) ~ True) =>
141   TFVec s a -> RangedWord u -> a -> TFVec s a
142 replace (TFVec xs) i y = TFVec $ replace' xs (toInteger i) y
143   where replace' []     _ _ = []
144         replace' (_:xs) 0 y = (y:xs)
145         replace' (x:xs) n y = x : (replace' xs (n-1) y)
146   
147 head :: PositiveT s => TFVec s a -> a
148 head = P.head . unTFVec
149
150 tail :: PositiveT s => TFVec s a -> TFVec (Pred s) a
151 tail = liftV P.tail
152
153 last :: PositiveT s => TFVec s a -> a
154 last = P.last . unTFVec
155
156 init :: PositiveT s => TFVec s a -> TFVec (Pred s) a
157 init = liftV P.init
158
159 take :: NaturalT i => i -> TFVec s a -> TFVec (Min s i) a
160 take i = liftV $ P.take (fromIntegerT i)
161
162 drop :: NaturalT i => i -> TFVec s a -> TFVec (s :-: (Min s i)) a
163 drop i = liftV $ P.drop (fromIntegerT i)
164
165 select :: (NaturalT f, NaturalT s, NaturalT n, (f :<: i) ~ True, 
166           (((s :*: n) :+: f) :<=: i) ~ True) => 
167           f -> s -> n -> TFVec i a -> TFVec n a
168 select f s n = liftV (select' f' s' n')
169   where (f', s', n') = (fromIntegerT f, fromIntegerT s, fromIntegerT n)
170         select' f s n = ((selectFirst0 s n).(P.drop f))
171         selectFirst0 :: Int -> Int -> [a] -> [a]
172         selectFirst0 s n l@(x:_)
173           | n > 0 = x : selectFirst0 s (n-1) (P.drop s l)
174           | otherwise = []
175         selectFirst0 _ 0 [] = []
176
177 (<+) :: TFVec s a -> a -> TFVec (Succ s) a
178 (<+) (TFVec xs) x = TFVec (xs P.++ [x])
179
180 (++) :: TFVec s a -> TFVec s2 a -> TFVec (s :+: s2) a
181 (++) = liftV2 (P.++)
182
183 infixl 5 <+
184 infixr 5 ++
185
186 map :: (a -> b) -> TFVec s a -> TFVec s b
187 map f = liftV (P.map f)
188
189 zipWith :: (a -> b -> c) -> TFVec s a -> TFVec s b -> TFVec s c
190 zipWith f = liftV2 (P.zipWith f)
191
192 foldl :: (a -> b -> a) -> a -> TFVec s b -> a
193 foldl f e = (P.foldl f e) . unTFVec
194
195 foldr :: (b -> a -> a) -> a -> TFVec s b -> a
196 foldr f e = (P.foldr f e) . unTFVec
197
198 zip :: TFVec s a -> TFVec s b -> TFVec s (a, b)
199 zip = liftV2 P.zip
200
201 unzip :: TFVec s (a, b) -> (TFVec s a, TFVec s b)
202 unzip (TFVec xs) = let (a,b) = P.unzip xs in (TFVec a, TFVec b)
203
204 shiftl :: (PositiveT s, NaturalT n, n ~ Pred s, s ~ Succ n) => 
205           TFVec s a -> a -> TFVec s a
206 shiftl xs x = x +> init xs
207
208 shiftr :: (PositiveT s, NaturalT n, n ~ Pred s, s ~ Succ n) => 
209           TFVec s a -> a -> TFVec s a
210 shiftr xs x = tail xs <+ x
211   
212 rotl :: forall s a . NaturalT s => TFVec s a -> TFVec s a
213 rotl = liftV rotl'
214   where vlen = fromIntegerT (undefined :: s)
215         rotl' [] = []
216         rotl' xs = let (i,[l]) = splitAt (vlen - 1) xs
217                    in l : i 
218
219 rotr :: NaturalT s => TFVec s a -> TFVec s a
220 rotr = liftV rotr'
221   where
222     rotr' [] = []
223     rotr' (x:xs) = xs P.++ [x] 
224
225 concat :: TFVec s1 (TFVec s2 a) -> TFVec (s1 :*: s2) a
226 concat = liftV (P.foldr ((P.++).unTFVec) [])
227
228 reverse :: TFVec s a -> TFVec s a
229 reverse = liftV P.reverse
230
231 iterate :: NaturalT s => s -> (a -> a) -> a -> TFVec s a
232 iterate s f x = let s' = fromIntegerT s in TFVec (P.take s' $ P.iterate f x)
233
234 generate :: NaturalT s => s -> (a -> a) -> a -> TFVec s a
235 generate s f x = let s' = fromIntegerT s in TFVec (P.take s' $ P.tail $ P.iterate f x)
236
237 copy :: NaturalT s => a -> TFVec s a
238 copy x = copyn (undefined :: s) x
239
240 copyn :: NaturalT s => s -> a -> TFVec s a
241 copyn s x = iterate s id x
242
243 -- =============
244 -- = Instances =
245 -- =============
246 instance Show a => Show (TFVec s a) where
247   showsPrec _ = showV.unTFVec
248     where showV []      = showString "<>"
249           showV (x:xs)  = showChar '<' . shows x . showl xs
250                             where showl []      = showChar '>'
251                                   showl (x:xs)  = showChar ',' . shows x .
252                                                   showl xs
253
254 instance (Read a, NaturalT nT) => Read (TFVec nT a) where
255   readsPrec _ str
256     | all fitsLength possibilities = P.map toReadS possibilities
257     | otherwise = error (fName P.++ ": string/dynamic length mismatch")
258     where 
259       fName = "Data.Param.TFVec.read"
260       expectedL = fromIntegerT (undefined :: nT)
261       possibilities = readTFVecList str
262       fitsLength (_, l, _) = l == expectedL
263       toReadS (xs, _, rest) = (TFVec xs, rest)
264       
265 instance NaturalT s => DF.Foldable (TFVec s) where
266  foldr = foldr
267  
268 instance NaturalT s => Functor (TFVec s) where
269  fmap = map
270
271 instance NaturalT s => DT.Traversable (TFVec s) where 
272   traverse f = (fmap TFVec).(DT.traverse f).unTFVec
273
274 instance (Lift a, NaturalT nT) => Lift (TFVec nT a) where
275   lift (TFVec xs) = [|  unsafeTFVecCoerse 
276                         $(decLiteralV (fromIntegerT (undefined :: nT))) 
277                         (TFVec xs) |]
278
279 -- ======================
280 -- = Internal Functions =
281 -- ======================
282 liftV :: ([a] -> [b]) -> TFVec nT a -> TFVec nT' b
283 liftV f = TFVec . f . unTFVec
284
285 liftV2 :: ([a] -> [b] -> [c]) -> TFVec s a -> TFVec s2 b -> TFVec s3 c
286 liftV2 f a b = TFVec (f (unTFVec a) (unTFVec b))
287
288 splitAtM :: Int -> [a] -> Maybe ([a],[a])
289 splitAtM n xs = splitAtM' n [] xs
290   where splitAtM' 0 xs ys = Just (xs, ys)
291         splitAtM' n xs (y:ys) | n > 0 = do
292           (ls, rs) <- splitAtM' (n-1) xs ys
293           return (y:ls,rs)
294         splitAtM' _ _ _ = Nothing
295
296 unsafeTFVecCoerse :: nT' -> TFVec nT a -> TFVec nT' a
297 unsafeTFVecCoerse _ (TFVec v) = (TFVec v)
298
299 unsafeVectorCPS :: forall a w . Integer -> [a] ->
300                         (forall s . NaturalT s => TFVec s a -> w) -> w
301 unsafeVectorCPS l xs f = reifyNaturalD l 
302                         (\(_ :: lt) -> f ((TFVec xs) :: (TFVec lt a)))
303
304 readTFVecList :: Read a => String -> [([a], Int, String)]
305 readTFVecList = readParen' False (\r -> [pr | ("<",s) <- lexTFVec r,
306                                               pr <- readl s])
307   where
308     readl   s = [([],0,t) | (">",t) <- lexTFVec s] P.++
309                             [(x:xs,1+n,u) | (x,t)       <- reads s,
310                                             (xs, n, u)  <- readl' t]
311     readl'  s = [([],0,t) | (">",t) <- lexTFVec s] P.++
312                             [(x:xs,1+n,v) | (",",t)   <- lex s,
313                                             (x,u)     <- reads t,
314                                             (xs,n,v)  <- readl' u]
315     readParen' b g  = if b then mandatory else optional
316       where optional r  = g r P.++ mandatory r
317             mandatory r = [(x,n,u) | ("(",s)  <- lexTFVec r,
318                                       (x,n,t) <- optional s,
319                                       (")",u) <- lexTFVec t]
320
321 -- Custom lexer for FSVecs, we cannot use lex directly because it considers
322 -- sequences of < and > as unique lexemes, and that breaks nested FSVecs, e.g.
323 -- <<1,2><3,4>>
324 lexTFVec :: ReadS String
325 lexTFVec ('>':rest) = [(">",rest)]
326 lexTFVec ('<':rest) = [("<",rest)]
327 lexTFVec str = lex str
328