673d69b3bb7370394c936e84022b56c0a25875d6
[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   , group
39   , (<+)
40   , (++)
41   , map
42   , zipWith
43   , foldl
44   , foldr
45   , zip
46   , unzip
47   , shiftl
48   , shiftr
49   , rotl
50   , rotr
51   , concat
52   , reverse
53   , iterate
54   , generate
55   , copy
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 {-# NOINLINE (+>) #-}
86 (+>) :: a -> TFVec s a -> TFVec (Succ s) a
87 x +> (TFVec xs) = TFVec (x:xs)
88
89 infix 5 +>
90
91 singleton :: a -> TFVec D1 a
92 singleton x = x +> empty
93
94 vectorCPS :: [a] -> (forall s . NaturalT s => TFVec s a -> w) -> w
95 vectorCPS xs = unsafeVectorCPS (toInteger (P.length xs)) xs
96
97 vectorTH :: Lift a => [a] -> ExpQ
98 vectorTH xs = (vectorCPS xs) lift
99
100 unsafeVector :: NaturalT s => s -> [a] -> TFVec s a
101 unsafeVector l xs
102   | fromIntegerT l /= P.length xs =
103     error (show 'unsafeVector P.++ ": dynamic/static lenght mismatch")
104   | otherwise = TFVec xs
105
106 readTFVec :: (Read a, NaturalT s) => String -> TFVec s a
107 readTFVec = read
108
109 readTFVecCPS :: Read a => String -> (forall s . NaturalT s => TFVec s a -> w) -> w
110 readTFVecCPS str = unsafeVectorCPS (toInteger l) xs
111  where fName = show 'readTFVecCPS
112        (xs,l) = case [(xs,l) | (xs,l,rest) <- readTFVecList str,  
113                            ("","") <- lexTFVec rest] of
114                        [(xs,l)] -> (xs,l)
115                        []   -> error (fName P.++ ": no parse")
116                        _    -> error (fName P.++ ": ambiguous parse")
117         
118 -- =======================
119 -- = Observing functions =
120 -- =======================
121 length :: forall s a . NaturalT s => TFVec s a -> Int
122 length _ = fromIntegerT (undefined :: s)
123
124 lengthT :: NaturalT s => TFVec s a -> s
125 lengthT = undefined
126
127 fromVector :: NaturalT s => TFVec s a -> [a]
128 fromVector (TFVec xs) = xs
129
130 null :: TFVec D0 a -> Bool
131 null _ = True
132
133 (!) ::  ( PositiveT s
134         , NaturalT u
135         , (s :>: u) ~ True) => TFVec s a -> RangedWord u -> a
136 (TFVec xs) ! i = xs !! (fromInteger (toInteger i))
137
138 -- ==========================
139 -- = Transforming functions =
140 -- ==========================
141 replace :: (PositiveT s, NaturalT u, (s :>: u) ~ True) =>
142   TFVec s a -> RangedWord u -> a -> TFVec s a
143 replace (TFVec xs) i y = TFVec $ replace' xs (toInteger i) y
144   where replace' []     _ _ = []
145         replace' (_:xs) 0 y = (y:xs)
146         replace' (x:xs) n y = x : (replace' xs (n-1) y)
147   
148 head :: PositiveT s => TFVec s a -> a
149 head = P.head . unTFVec
150
151 tail :: PositiveT s => TFVec s a -> TFVec (Pred s) a
152 tail = liftV P.tail
153
154 last :: PositiveT s => TFVec s a -> a
155 last = P.last . unTFVec
156
157 init :: PositiveT s => TFVec s a -> TFVec (Pred s) a
158 init = liftV P.init
159
160 take :: NaturalT i => i -> TFVec s a -> TFVec (Min s i) a
161 take i = liftV $ P.take (fromIntegerT i)
162
163 drop :: NaturalT i => i -> TFVec s a -> TFVec (s :-: (Min s i)) a
164 drop i = liftV $ P.drop (fromIntegerT i)
165
166 select :: (NaturalT f, NaturalT s, NaturalT n, (f :<: i) ~ True, 
167           (((s :*: n) :+: f) :<=: i) ~ True) => 
168           f -> s -> n -> TFVec i a -> TFVec n a
169 select f s n = liftV (select' f' s' n')
170   where (f', s', n') = (fromIntegerT f, fromIntegerT s, fromIntegerT n)
171         select' f s n = ((selectFirst0 s n).(P.drop f))
172         selectFirst0 :: Int -> Int -> [a] -> [a]
173         selectFirst0 s n l@(x:_)
174           | n > 0 = x : selectFirst0 s (n-1) (P.drop s l)
175           | otherwise = []
176         selectFirst0 _ 0 [] = []
177
178 group :: PositiveT n => n -> TFVec s a -> TFVec (Div s n) (TFVec n a)
179 group n = liftV (group' (fromIntegerT n))
180   where group' :: Int -> [a] -> [TFVec s a]
181         group' n xs = case splitAtM n xs of
182                         Nothing -> []
183                         Just (ls, rs) -> TFVec ls : group' n rs
184
185 (<+) :: TFVec s a -> a -> TFVec (Succ s) a
186 (<+) (TFVec xs) x = TFVec (xs P.++ [x])
187
188 (++) :: TFVec s a -> TFVec s2 a -> TFVec (s :+: s2) a
189 (++) = liftV2 (P.++)
190
191 infixl 5 <+
192 infixr 5 ++
193
194 map :: (a -> b) -> TFVec s a -> TFVec s b
195 map f = liftV (P.map f)
196
197 zipWith :: (a -> b -> c) -> TFVec s a -> TFVec s b -> TFVec s c
198 zipWith f = liftV2 (P.zipWith f)
199
200 foldl :: (a -> b -> a) -> a -> TFVec s b -> a
201 foldl f e = (P.foldl f e) . unTFVec
202
203 foldr :: (b -> a -> a) -> a -> TFVec s b -> a
204 foldr f e = (P.foldr f e) . unTFVec
205
206 zip :: TFVec s a -> TFVec s b -> TFVec s (a, b)
207 zip = liftV2 P.zip
208
209 unzip :: TFVec s (a, b) -> (TFVec s a, TFVec s b)
210 unzip (TFVec xs) = let (a,b) = P.unzip xs in (TFVec a, TFVec b)
211
212 shiftl :: (PositiveT s, NaturalT n, n ~ Pred s, s ~ Succ n) => 
213           TFVec s a -> a -> TFVec s a
214 shiftl xs x = x +> init xs
215
216 shiftr :: (PositiveT s, NaturalT n, n ~ Pred s, s ~ Succ n) => 
217           TFVec s a -> a -> TFVec s a
218 shiftr xs x = tail xs <+ x
219   
220 rotl :: (PositiveT s, s ~ Succ (Pred s)) => TFVec s a -> TFVec s a
221 rotl xs = last xs +> init xs
222
223 class Rotr a where rotr :: a -> a
224 instance Rotr (TFVec D0 a) where rotr xs = xs
225 instance (PositiveT s, s ~ Succ (Pred s)) => Rotr (TFVec s a) where rotr xs = tail xs <+ head xs
226
227 concat :: TFVec s1 (TFVec s2 a) -> TFVec (s1 :*: s2) a
228 concat = liftV (P.foldr ((P.++).unTFVec) [])
229
230 reverse :: TFVec s a -> TFVec s a
231 reverse = liftV P.reverse
232
233 iterate :: NaturalT s => s -> (a -> a) -> a -> TFVec s a
234 iterate s f x = let s' = fromIntegerT s in TFVec (P.take s' $ P.iterate f x)
235
236 generate :: NaturalT s => s -> (a -> a) -> a -> TFVec s a
237 generate s f x = let s' = fromIntegerT s in TFVec (P.take s' $ P.tail $ P.iterate f x)
238
239 copy :: NaturalT s => s -> a -> TFVec s a
240 copy s x = iterate s id x
241
242 -- =============
243 -- = Instances =
244 -- =============
245 instance Show a => Show (TFVec s a) where
246   showsPrec _ = showV.unTFVec
247     where showV []      = showString "<>"
248           showV (x:xs)  = showChar '<' . shows x . showl xs
249                             where showl []      = showChar '>'
250                                   showl (x:xs)  = showChar ',' . shows x .
251                                                   showl xs
252
253 instance (Read a, NaturalT nT) => Read (TFVec nT a) where
254   readsPrec _ str
255     | all fitsLength possibilities = P.map toReadS possibilities
256     | otherwise = error (fName P.++ ": string/dynamic length mismatch")
257     where 
258       fName = "Data.Param.TFVec.read"
259       expectedL = fromIntegerT (undefined :: nT)
260       possibilities = readTFVecList str
261       fitsLength (_, l, _) = l == expectedL
262       toReadS (xs, _, rest) = (TFVec xs, rest)
263       
264 instance NaturalT s => DF.Foldable (TFVec s) where
265  foldr = foldr
266  
267 instance NaturalT s => Functor (TFVec s) where
268  fmap = map
269
270 instance NaturalT s => DT.Traversable (TFVec s) where 
271   traverse f = (fmap TFVec).(DT.traverse f).unTFVec
272
273 instance (Lift a, NaturalT nT) => Lift (TFVec nT a) where
274   lift (TFVec xs) = [|  unsafeTFVecCoerse 
275                         $(decLiteralV (fromIntegerT (undefined :: nT))) 
276                         (TFVec xs) |]
277
278 -- ======================
279 -- = Internal Functions =
280 -- ======================
281 liftV :: ([a] -> [b]) -> TFVec nT a -> TFVec nT' b
282 liftV f = TFVec . f . unTFVec
283
284 liftV2 :: ([a] -> [b] -> [c]) -> TFVec s a -> TFVec s2 b -> TFVec s3 c
285 liftV2 f a b = TFVec (f (unTFVec a) (unTFVec b))
286
287 splitAtM :: Int -> [a] -> Maybe ([a],[a])
288 splitAtM n xs = splitAtM' n [] xs
289   where splitAtM' 0 xs ys = Just (xs, ys)
290         splitAtM' n xs (y:ys) | n > 0 = do
291           (ls, rs) <- splitAtM' (n-1) xs ys
292           return (y:ls,rs)
293         splitAtM' _ _ _ = Nothing
294
295 unsafeTFVecCoerse :: nT' -> TFVec nT a -> TFVec nT' a
296 unsafeTFVecCoerse _ (TFVec v) = (TFVec v)
297
298 unsafeVectorCPS :: forall a w . Integer -> [a] ->
299                         (forall s . NaturalT s => TFVec s a -> w) -> w
300 unsafeVectorCPS l xs f = reifyNaturalD l 
301                         (\(_ :: lt) -> f ((TFVec xs) :: (TFVec lt a)))
302
303 readTFVecList :: Read a => String -> [([a], Int, String)]
304 readTFVecList = readParen' False (\r -> [pr | ("<",s) <- lexTFVec r,
305                                               pr <- readl s])
306   where
307     readl   s = [([],0,t) | (">",t) <- lexTFVec s] P.++
308                             [(x:xs,1+n,u) | (x,t)       <- reads s,
309                                             (xs, n, u)  <- readl' t]
310     readl'  s = [([],0,t) | (">",t) <- lexTFVec s] P.++
311                             [(x:xs,1+n,v) | (",",t)   <- lex s,
312                                             (x,u)     <- reads t,
313                                             (xs,n,v)  <- readl' u]
314     readParen' b g  = if b then mandatory else optional
315       where optional r  = g r P.++ mandatory r
316             mandatory r = [(x,n,u) | ("(",s)  <- lexTFVec r,
317                                       (x,n,t) <- optional s,
318                                       (")",u) <- lexTFVec t]
319
320 -- Custom lexer for FSVecs, we cannot use lex directly because it considers
321 -- sequences of < and > as unique lexemes, and that breaks nested FSVecs, e.g.
322 -- <<1,2><3,4>>
323 lexTFVec :: ReadS String
324 lexTFVec ('>':rest) = [(">",rest)]
325 lexTFVec ('<':rest) = [("<",rest)]
326 lexTFVec str = lex str
327