50b2fda258b44de6c285aeacae5889aeeddd5ab9
[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   , copyn
57   ) where
58     
59
60 import Types
61 import Types.Data.Num.Decimal.Literals.TH
62 import Data.RangedWord
63
64 import Data.Generics (Data, Typeable)
65 import qualified Prelude as P
66 import Prelude hiding (
67   null, length, head, tail, last, init, take, drop, (++), map, foldl, foldr,
68   zipWith, zip, unzip, concat, reverse, iterate )
69 import qualified Data.Foldable as DF (Foldable, foldr)
70 import qualified Data.Traversable as DT (Traversable(traverse))
71 import Language.Haskell.TH
72 import Language.Haskell.TH.Syntax (Lift(..))
73
74 newtype (NaturalT s) => TFVec s a = TFVec {unTFVec :: [a]}
75   deriving (Eq, Typeable)
76
77 deriving instance (NaturalT s, Typeable s, Data s, Typeable a, Data a) => Data (TFVec s a)
78
79 -- ==========================
80 -- = Constructing functions =
81 -- ==========================
82                                                   
83 empty :: TFVec D0 a
84 empty = TFVec []
85
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 rotr :: (PositiveT s, s ~ Succ (Pred s)) => TFVec s a -> TFVec s a
224 rotr xs = tail xs <+ head xs
225
226 concat :: TFVec s1 (TFVec s2 a) -> TFVec (s1 :*: s2) a
227 concat = liftV (P.foldr ((P.++).unTFVec) [])
228
229 reverse :: TFVec s a -> TFVec s a
230 reverse = liftV P.reverse
231
232 iterate :: NaturalT s => s -> (a -> a) -> a -> TFVec s a
233 iterate s f x = let s' = fromIntegerT s in TFVec (P.take s' $ P.iterate f x)
234
235 generate :: NaturalT s => s -> (a -> a) -> a -> TFVec s a
236 generate s f x = let s' = fromIntegerT s in TFVec (P.take s' $ P.tail $ P.iterate f x)
237
238 copy :: NaturalT s => a -> TFVec s a
239 copy x = copyn (undefined :: s) x
240
241 copyn :: NaturalT s => s -> a -> TFVec s a
242 copyn s x = iterate s id x
243
244 -- =============
245 -- = Instances =
246 -- =============
247 instance Show a => Show (TFVec s a) where
248   showsPrec _ = showV.unTFVec
249     where showV []      = showString "<>"
250           showV (x:xs)  = showChar '<' . shows x . showl xs
251                             where showl []      = showChar '>'
252                                   showl (x:xs)  = showChar ',' . shows x .
253                                                   showl xs
254
255 instance (Read a, NaturalT nT) => Read (TFVec nT a) where
256   readsPrec _ str
257     | all fitsLength possibilities = P.map toReadS possibilities
258     | otherwise = error (fName P.++ ": string/dynamic length mismatch")
259     where 
260       fName = "Data.Param.TFVec.read"
261       expectedL = fromIntegerT (undefined :: nT)
262       possibilities = readTFVecList str
263       fitsLength (_, l, _) = l == expectedL
264       toReadS (xs, _, rest) = (TFVec xs, rest)
265       
266 instance NaturalT s => DF.Foldable (TFVec s) where
267  foldr = foldr
268  
269 instance NaturalT s => Functor (TFVec s) where
270  fmap = map
271
272 instance NaturalT s => DT.Traversable (TFVec s) where 
273   traverse f = (fmap TFVec).(DT.traverse f).unTFVec
274
275 instance (Lift a, NaturalT nT) => Lift (TFVec nT a) where
276   lift (TFVec xs) = [|  unsafeTFVecCoerse 
277                         $(decLiteralV (fromIntegerT (undefined :: nT))) 
278                         (TFVec xs) |]
279
280 -- ======================
281 -- = Internal Functions =
282 -- ======================
283 liftV :: ([a] -> [b]) -> TFVec nT a -> TFVec nT' b
284 liftV f = TFVec . f . unTFVec
285
286 liftV2 :: ([a] -> [b] -> [c]) -> TFVec s a -> TFVec s2 b -> TFVec s3 c
287 liftV2 f a b = TFVec (f (unTFVec a) (unTFVec b))
288
289 splitAtM :: Int -> [a] -> Maybe ([a],[a])
290 splitAtM n xs = splitAtM' n [] xs
291   where splitAtM' 0 xs ys = Just (xs, ys)
292         splitAtM' n xs (y:ys) | n > 0 = do
293           (ls, rs) <- splitAtM' (n-1) xs ys
294           return (y:ls,rs)
295         splitAtM' _ _ _ = Nothing
296
297 unsafeTFVecCoerse :: nT' -> TFVec nT a -> TFVec nT' a
298 unsafeTFVecCoerse _ (TFVec v) = (TFVec v)
299
300 unsafeVectorCPS :: forall a w . Integer -> [a] ->
301                         (forall s . NaturalT s => TFVec s a -> w) -> w
302 unsafeVectorCPS l xs f = reifyNaturalD l 
303                         (\(_ :: lt) -> f ((TFVec xs) :: (TFVec lt a)))
304
305 readTFVecList :: Read a => String -> [([a], Int, String)]
306 readTFVecList = readParen' False (\r -> [pr | ("<",s) <- lexTFVec r,
307                                               pr <- readl s])
308   where
309     readl   s = [([],0,t) | (">",t) <- lexTFVec s] P.++
310                             [(x:xs,1+n,u) | (x,t)       <- reads s,
311                                             (xs, n, u)  <- readl' t]
312     readl'  s = [([],0,t) | (">",t) <- lexTFVec s] P.++
313                             [(x:xs,1+n,v) | (",",t)   <- lex s,
314                                             (x,u)     <- reads t,
315                                             (xs,n,v)  <- readl' u]
316     readParen' b g  = if b then mandatory else optional
317       where optional r  = g r P.++ mandatory r
318             mandatory r = [(x,n,u) | ("(",s)  <- lexTFVec r,
319                                       (x,n,t) <- optional s,
320                                       (")",u) <- lexTFVec t]
321
322 -- Custom lexer for FSVecs, we cannot use lex directly because it considers
323 -- sequences of < and > as unique lexemes, and that breaks nested FSVecs, e.g.
324 -- <<1,2><3,4>>
325 lexTFVec :: ReadS String
326 lexTFVec ('>':rest) = [(">",rest)]
327 lexTFVec ('<':rest) = [("<",rest)]
328 lexTFVec str = lex str
329