Fix backpermute
[darcs-mirrors/vector.git] / Data / Vector / Generic.hs
1 {-# LANGUAGE Rank2Types, MultiParamTypeClasses, FlexibleContexts,
2 ScopedTypeVariables #-}
3 -- |
4 -- Module : Data.Vector.Generic
5 -- Copyright : (c) Roman Leshchinskiy 2008-2009
6 -- License : BSD-style
7 --
8 -- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
9 -- Stability : experimental
10 -- Portability : non-portable
11 --
12 -- Generic interface to pure vectors
13 --
14
15 #include "phases.h"
16
17 module Data.Vector.Generic (
18 -- * Immutable vectors
19 Vector(..),
20
21 -- * Length information
22 length, null,
23
24 -- * Construction
25 empty, singleton, cons, snoc, replicate, (++), copy,
26
27 -- * Accessing individual elements
28 (!), head, last, indexM, headM, lastM,
29
30 -- * Subvectors
31 slice, init, tail, take, drop,
32
33 -- * Permutations
34 accum, (//), update, backpermute, reverse,
35
36 -- * Mapping
37 map, concatMap,
38
39 -- * Zipping and unzipping
40 zipWith, zipWith3, zip, zip3, unzip, unzip3,
41
42 -- * Comparisons
43 eq, cmp,
44
45 -- * Filtering
46 filter, takeWhile, dropWhile,
47
48 -- * Searching
49 elem, notElem, find, findIndex,
50
51 -- * Folding
52 foldl, foldl1, foldl', foldl1', foldr, foldr1,
53
54 -- * Specialised folds
55 and, or, sum, product, maximum, minimum,
56
57 -- * Unfolding
58 unfoldr,
59
60 -- * Scans
61 prescanl, prescanl',
62 postscanl, postscanl',
63 scanl, scanl', scanl1, scanl1',
64
65 -- * Enumeration
66 enumFromTo, enumFromThenTo,
67
68 -- * Conversion to/from lists
69 toList, fromList,
70
71 -- * Conversion to/from Streams
72 stream, unstream,
73
74 -- * MVector-based initialisation
75 new
76 ) where
77
78 import Data.Vector.Generic.Mutable ( MVector )
79
80 import qualified Data.Vector.Generic.New as New
81 import Data.Vector.Generic.New ( New )
82
83 import qualified Data.Vector.Fusion.Stream as Stream
84 import Data.Vector.Fusion.Stream ( Stream, MStream, inplace, inplace' )
85 import qualified Data.Vector.Fusion.Stream.Monadic as MStream
86 import Data.Vector.Fusion.Stream.Size
87 import Data.Vector.Fusion.Util
88
89 import Control.Exception ( assert )
90
91 import Prelude hiding ( length, null,
92 replicate, (++),
93 head, last,
94 init, tail, take, drop, reverse,
95 map, concatMap,
96 zipWith, zipWith3, zip, zip3, unzip, unzip3,
97 filter, takeWhile, dropWhile,
98 elem, notElem,
99 foldl, foldl1, foldr, foldr1,
100 and, or, sum, product, maximum, minimum,
101 scanl, scanl1,
102 enumFromTo, enumFromThenTo )
103
104 -- | Class of immutable vectors.
105 --
106 class Vector v a where
107 -- | Construct a pure vector from a monadic initialiser (not fusible!)
108 vnew :: (forall mv m. MVector mv m a => m (mv a)) -> v a
109
110 -- | Length of the vector (not fusible!)
111 vlength :: v a -> Int
112
113 -- | Yield a part of the vector without copying it. No range checks!
114 unsafeSlice :: v a -> Int -> Int -> v a
115
116 -- | Yield the element at the given position in a monad. The monad allows us
117 -- to be strict in the vector if we want. Suppose we had
118 --
119 -- > unsafeIndex :: v a -> Int -> a
120 --
121 -- instead. Now, if we wanted to copy a vector, we'd do something like
122 --
123 -- > copy mv v ... = ... unsafeWrite mv i (unsafeIndex v i) ...
124 --
125 -- For lazy vectors, the indexing would not be evaluated which means that we
126 -- would retain a reference to the original vector in each element we write.
127 -- This is not what we want!
128 --
129 -- With 'unsafeIndexM', we can do
130 --
131 -- > copy mv v ... = ... case unsafeIndexM v i of
132 -- > Box x -> unsafeWrite mv i x ...
133 --
134 -- which does not have this problem because indexing (but not the returned
135 -- element!) is evaluated immediately.
136 --
137 unsafeIndexM :: Monad m => v a -> Int -> m a
138
139 -- Fusion
140 -- ------
141
142 -- | Construct a pure vector from a monadic initialiser
143 new :: Vector v a => New a -> v a
144 {-# INLINE new #-}
145 new m = new' undefined m
146
147 -- | Same as 'new' but with a dummy argument necessary for correctly typing
148 -- the rule @uninplace@.
149 --
150 -- See http://hackage.haskell.org/trac/ghc/ticket/2600
151 new' :: Vector v a => v a -> New a -> v a
152 {-# INLINE_STREAM new' #-}
153 new' _ m = vnew (New.run m)
154
155 -- | Convert a vector to a 'Stream'
156 stream :: Vector v a => v a -> Stream a
157 {-# INLINE_STREAM stream #-}
158 stream v = v `seq` (Stream.unfoldr get 0 `Stream.sized` Exact n)
159 where
160 n = length v
161
162 -- NOTE: the False case comes first in Core so making it the recursive one
163 -- makes the code easier to read
164 {-# INLINE get #-}
165 get i | i >= n = Nothing
166 | otherwise = case unsafeIndexM v i of Box x -> Just (x, i+1)
167
168 -- | Create a vector from a 'Stream'
169 unstream :: Vector v a => Stream a -> v a
170 {-# INLINE unstream #-}
171 unstream s = new (New.unstream s)
172
173 {-# RULES
174
175 "stream/unstream [Vector]" forall v s.
176 stream (new' v (New.unstream s)) = s
177
178 "New.unstream/stream/new [Vector]" forall v p.
179 New.unstream (stream (new' v p)) = p
180
181 #-}
182
183 {-# RULES
184
185 "inplace [Vector]"
186 forall (f :: forall m. Monad m => MStream m a -> MStream m a) v m.
187 New.unstream (inplace f (stream (new' v m))) = New.transform f m
188
189 "uninplace [Vector]"
190 forall (f :: forall m. Monad m => MStream m a -> MStream m a) v m.
191 stream (new' v (New.transform f m)) = inplace f (stream (new' v m))
192
193 #-}
194
195 -- Length
196 -- ------
197
198 length :: Vector v a => v a -> Int
199 {-# INLINE_STREAM length #-}
200 length v = vlength v
201
202 {-# RULES
203
204 "length/unstream [Vector]" forall v s.
205 length (new' v (New.unstream s)) = Stream.length s
206
207 #-}
208
209 null :: Vector v a => v a -> Bool
210 {-# INLINE_STREAM null #-}
211 null v = vlength v == 0
212
213 {-# RULES
214
215 "null/unstream [Vector]" forall v s.
216 null (new' v (New.unstream s)) = Stream.null s
217
218 #-}
219
220 -- Construction
221 -- ------------
222
223 -- | Empty vector
224 empty :: Vector v a => v a
225 {-# INLINE empty #-}
226 empty = unstream Stream.empty
227
228 -- | Vector with exaclty one element
229 singleton :: Vector v a => a -> v a
230 {-# INLINE singleton #-}
231 singleton x = unstream (Stream.singleton x)
232
233 -- | Vector of the given length with the given value in each position
234 replicate :: Vector v a => Int -> a -> v a
235 {-# INLINE replicate #-}
236 replicate n = unstream . Stream.replicate n
237
238 -- | Prepend an element
239 cons :: Vector v a => a -> v a -> v a
240 {-# INLINE cons #-}
241 cons x = unstream . Stream.cons x . stream
242
243 -- | Append an element
244 snoc :: Vector v a => v a -> a -> v a
245 {-# INLINE snoc #-}
246 snoc v = unstream . Stream.snoc (stream v)
247
248 infixr 5 ++
249 -- | Concatenate two vectors
250 (++) :: Vector v a => v a -> v a -> v a
251 {-# INLINE (++) #-}
252 v ++ w = unstream (stream v Stream.++ stream w)
253
254 -- | Create a copy of a vector. Useful when dealing with slices.
255 copy :: Vector v a => v a -> v a
256 {-# INLINE_STREAM copy #-}
257 copy = unstream . stream
258
259 {-# RULES
260
261 "copy/unstream [Vector]" forall v s.
262 copy (new' v (New.unstream s)) = new' v (New.unstream s)
263
264 #-}
265
266 -- Accessing individual elements
267 -- -----------------------------
268
269 -- | Indexing
270 (!) :: Vector v a => v a -> Int -> a
271 {-# INLINE_STREAM (!) #-}
272 v ! i = assert (i >= 0 && i < length v)
273 $ unId (unsafeIndexM v i)
274
275 -- | First element
276 head :: Vector v a => v a -> a
277 {-# INLINE_STREAM head #-}
278 head v = v ! 0
279
280 -- | Last element
281 last :: Vector v a => v a -> a
282 {-# INLINE_STREAM last #-}
283 last v = v ! (length v - 1)
284
285 {-# RULES
286
287 "(!)/unstream [Vector]" forall v i s.
288 new' v (New.unstream s) ! i = s Stream.!! i
289
290 "head/unstream [Vector]" forall v s.
291 head (new' v (New.unstream s)) = Stream.head s
292
293 "last/unstream [Vector]" forall v s.
294 last (new' v (New.unstream s)) = Stream.last s
295
296 #-}
297
298 -- | Monadic indexing which can be strict in the vector while remaining lazy in
299 -- the element.
300 indexM :: (Vector v a, Monad m) => v a -> Int -> m a
301 {-# INLINE_STREAM indexM #-}
302 indexM v i = assert (i >= 0 && i < length v)
303 $ unsafeIndexM v i
304
305 headM :: (Vector v a, Monad m) => v a -> m a
306 {-# INLINE_STREAM headM #-}
307 headM v = indexM v 0
308
309 lastM :: (Vector v a, Monad m) => v a -> m a
310 {-# INLINE_STREAM lastM #-}
311 lastM v = indexM v (length v - 1)
312
313 -- FIXME: the rhs of these rules are lazy in the stream which is WRONG
314 {- RULES
315
316 "indexM/unstream [Vector]" forall v i s.
317 indexM (new' v (New.unstream s)) i = return (s Stream.!! i)
318
319 "headM/unstream [Vector]" forall v s.
320 headM (new' v (New.unstream s)) = return (Stream.head s)
321
322 "lastM/unstream [Vector]" forall v s.
323 lastM (new' v (New.unstream s)) = return (Stream.last s)
324
325 -}
326
327 -- Subarrays
328 -- ---------
329
330 -- FIXME: slicing doesn't work with the inplace stuff at the moment
331
332 -- | Yield a part of the vector without copying it. Safer version of
333 -- 'unsafeSlice'.
334 slice :: Vector v a => v a -> Int -- ^ starting index
335 -> Int -- ^ length
336 -> v a
337 {-# INLINE_STREAM slice #-}
338 slice v i n = assert (i >= 0 && n >= 0 && i+n <= length v)
339 $ unsafeSlice v i n
340
341 -- | Yield all but the last element without copying.
342 init :: Vector v a => v a -> v a
343 {-# INLINE_STREAM init #-}
344 init v = slice v 0 (length v - 1)
345
346 -- | All but the first element (without copying).
347 tail :: Vector v a => v a -> v a
348 {-# INLINE_STREAM tail #-}
349 tail v = slice v 1 (length v - 1)
350
351 -- | Yield the first @n@ elements without copying.
352 take :: Vector v a => Int -> v a -> v a
353 {-# INLINE_STREAM take #-}
354 take n v = slice v 0 (min n' (length v))
355 where n' = max n 0
356
357 -- | Yield all but the first @n@ elements without copying.
358 drop :: Vector v a => Int -> v a -> v a
359 {-# INLINE_STREAM drop #-}
360 drop n v = slice v (min n' len) (max 0 (len - n'))
361 where n' = max n 0
362 len = length v
363
364 {-# RULES
365
366 "slice/new [Vector]" forall v p i n.
367 slice (new' v p) i n = new' v (New.slice p i n)
368
369 "init/new [Vector]" forall v p.
370 init (new' v p) = new' v (New.init p)
371
372 "tail/new [Vector]" forall v p.
373 tail (new' v p) = new' v (New.tail p)
374
375 "take/new [Vector]" forall n v p.
376 take n (new' v p) = new' v (New.take n p)
377
378 "drop/new [Vector]" forall n v p.
379 drop n (new' v p) = new' v (New.drop n p)
380
381 #-}
382
383 -- Permutations
384 -- ------------
385
386 accum :: Vector v a => (a -> b -> a) -> v a -> [(Int,b)] -> v a
387 {-# INLINE accum #-}
388 accum f v us = new (New.accum f (New.unstream (stream v))
389 (Stream.fromList us))
390
391 (//) :: Vector v a => v a -> [(Int, a)] -> v a
392 {-# INLINE (//) #-}
393 v // us = new (New.update (New.unstream (stream v))
394 (Stream.fromList us))
395
396 update :: (Vector v a, Vector v (Int, a)) => v a -> v (Int, a) -> v a
397 {-# INLINE update #-}
398 update v w = new (New.update (New.unstream (stream v)) (stream w))
399
400 -- This somewhat non-intuitive definition ensures that the resulting vector
401 -- does not retain references to the original one even if it is lazy in its
402 -- elements. This would not be the case if we simply used
403 --
404 -- backpermute v is = map (v!) is
405 backpermute :: (Vector v a, Vector v Int) => v a -> v Int -> v a
406 {-# INLINE backpermute #-}
407 backpermute v is = seq v
408 $ unstream
409 $ Stream.unbox
410 $ Stream.map (indexM v)
411 $ stream is
412
413 reverse :: (Vector v a) => v a -> v a
414 {-# INLINE reverse #-}
415 reverse = new . New.reverse . New.unstream . stream
416
417 -- Mapping
418 -- -------
419
420 -- | Map a function over a vector
421 map :: (Vector v a, Vector v b) => (a -> b) -> v a -> v b
422 {-# INLINE map #-}
423 map f = unstream . inplace' (MStream.map f) . stream
424
425 concatMap :: (Vector v a, Vector v b) => (a -> v b) -> v a -> v b
426 {-# INLINE concatMap #-}
427 concatMap f = unstream . Stream.concatMap (stream . f) . stream
428
429 -- Zipping/unzipping
430 -- -----------------
431
432 -- | Zip two vectors with the given function.
433 zipWith :: (Vector v a, Vector v b, Vector v c) => (a -> b -> c) -> v a -> v b -> v c
434 {-# INLINE zipWith #-}
435 zipWith f xs ys = unstream (Stream.zipWith f (stream xs) (stream ys))
436
437 -- | Zip three vectors with the given function.
438 zipWith3 :: (Vector v a, Vector v b, Vector v c, Vector v d) => (a -> b -> c -> d) -> v a -> v b -> v c -> v d
439 {-# INLINE zipWith3 #-}
440 zipWith3 f xs ys zs = unstream (Stream.zipWith3 f (stream xs) (stream ys) (stream zs))
441
442 zip :: (Vector v a, Vector v b, Vector v (a,b)) => v a -> v b -> v (a, b)
443 {-# INLINE zip #-}
444 zip = zipWith (,)
445
446 zip3 :: (Vector v a, Vector v b, Vector v c, Vector v (a, b, c)) => v a -> v b -> v c -> v (a, b, c)
447 {-# INLINE zip3 #-}
448 zip3 = zipWith3 (,,)
449
450 unzip :: (Vector v a, Vector v b, Vector v (a,b)) => v (a, b) -> (v a, v b)
451 {-# INLINE unzip #-}
452 unzip xs = (map fst xs, map snd xs)
453
454 unzip3 :: (Vector v a, Vector v b, Vector v c, Vector v (a, b, c)) => v (a, b, c) -> (v a, v b, v c)
455 {-# INLINE unzip3 #-}
456 unzip3 xs = (map (\(a, b, c) -> a) xs, map (\(a, b, c) -> b) xs, map (\(a, b, c) -> c) xs)
457
458 -- Comparisons
459 -- -----------
460
461 eq :: (Vector v a, Eq a) => v a -> v a -> Bool
462 {-# INLINE eq #-}
463 xs `eq` ys = stream xs == stream ys
464
465 cmp :: (Vector v a, Ord a) => v a -> v a -> Ordering
466 {-# INLINE cmp #-}
467 cmp xs ys = compare (stream xs) (stream ys)
468
469 -- Filtering
470 -- ---------
471
472 -- | Drop elements which do not satisfy the predicate
473 filter :: Vector v a => (a -> Bool) -> v a -> v a
474 {-# INLINE filter #-}
475 filter f = unstream . inplace (MStream.filter f) . stream
476
477 -- | Yield the longest prefix of elements satisfying the predicate.
478 takeWhile :: Vector v a => (a -> Bool) -> v a -> v a
479 {-# INLINE takeWhile #-}
480 takeWhile f = unstream . Stream.takeWhile f . stream
481
482 -- | Drop the longest prefix of elements that satisfy the predicate.
483 dropWhile :: Vector v a => (a -> Bool) -> v a -> v a
484 {-# INLINE dropWhile #-}
485 dropWhile f = unstream . Stream.dropWhile f . stream
486
487 -- Searching
488 -- ---------
489
490 infix 4 `elem`
491 -- | Check whether the vector contains an element
492 elem :: (Vector v a, Eq a) => a -> v a -> Bool
493 {-# INLINE elem #-}
494 elem x = Stream.elem x . stream
495
496 infix 4 `notElem`
497 -- | Inverse of `elem`
498 notElem :: (Vector v a, Eq a) => a -> v a -> Bool
499 {-# INLINE notElem #-}
500 notElem x = Stream.notElem x . stream
501
502 -- | Yield 'Just' the first element matching the predicate or 'Nothing' if no
503 -- such element exists.
504 find :: Vector v a => (a -> Bool) -> v a -> Maybe a
505 {-# INLINE find #-}
506 find f = Stream.find f . stream
507
508 -- | Yield 'Just' the index of the first element matching the predicate or
509 -- 'Nothing' if no such element exists.
510 findIndex :: Vector v a => (a -> Bool) -> v a -> Maybe Int
511 {-# INLINE findIndex #-}
512 findIndex f = Stream.findIndex f . stream
513
514 -- Folding
515 -- -------
516
517 -- | Left fold
518 foldl :: Vector v b => (a -> b -> a) -> a -> v b -> a
519 {-# INLINE foldl #-}
520 foldl f z = Stream.foldl f z . stream
521
522 -- | Lefgt fold on non-empty vectors
523 foldl1 :: Vector v a => (a -> a -> a) -> v a -> a
524 {-# INLINE foldl1 #-}
525 foldl1 f = Stream.foldl1 f . stream
526
527 -- | Left fold with strict accumulator
528 foldl' :: Vector v b => (a -> b -> a) -> a -> v b -> a
529 {-# INLINE foldl' #-}
530 foldl' f z = Stream.foldl' f z . stream
531
532 -- | Left fold on non-empty vectors with strict accumulator
533 foldl1' :: Vector v a => (a -> a -> a) -> v a -> a
534 {-# INLINE foldl1' #-}
535 foldl1' f = Stream.foldl1' f . stream
536
537 -- | Right fold
538 foldr :: Vector v a => (a -> b -> b) -> b -> v a -> b
539 {-# INLINE foldr #-}
540 foldr f z = Stream.foldr f z . stream
541
542 -- | Right fold on non-empty vectors
543 foldr1 :: Vector v a => (a -> a -> a) -> v a -> a
544 {-# INLINE foldr1 #-}
545 foldr1 f = Stream.foldr1 f . stream
546
547 -- Specialised folds
548 -- -----------------
549
550 and :: Vector v Bool => v Bool -> Bool
551 {-# INLINE and #-}
552 and = Stream.and . stream
553
554 or :: Vector v Bool => v Bool -> Bool
555 {-# INLINE or #-}
556 or = Stream.or . stream
557
558 sum :: (Vector v a, Num a) => v a -> a
559 {-# INLINE sum #-}
560 sum = Stream.foldl' (+) 0 . stream
561
562 product :: (Vector v a, Num a) => v a -> a
563 {-# INLINE product #-}
564 product = Stream.foldl' (*) 1 . stream
565
566 maximum :: (Vector v a, Ord a) => v a -> a
567 {-# INLINE maximum #-}
568 maximum = Stream.foldl1' max . stream
569
570 minimum :: (Vector v a, Ord a) => v a -> a
571 {-# INLINE minimum #-}
572 minimum = Stream.foldl1' min . stream
573
574 -- Unfolding
575 -- ---------
576
577 unfoldr :: Vector v a => (b -> Maybe (a, b)) -> b -> v a
578 {-# INLINE unfoldr #-}
579 unfoldr f = unstream . Stream.unfoldr f
580
581 -- Scans
582 -- -----
583
584 -- | Prefix scan
585 prescanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
586 {-# INLINE prescanl #-}
587 prescanl f z = unstream . inplace' (MStream.prescanl f z) . stream
588
589 -- | Prefix scan with strict accumulator
590 prescanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
591 {-# INLINE prescanl' #-}
592 prescanl' f z = unstream . inplace' (MStream.prescanl' f z) . stream
593
594 -- | Suffix scan
595 postscanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
596 {-# INLINE postscanl #-}
597 postscanl f z = unstream . inplace' (MStream.postscanl f z) . stream
598
599 -- | Suffix scan with strict accumulator
600 postscanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
601 {-# INLINE postscanl' #-}
602 postscanl' f z = unstream . inplace' (MStream.postscanl' f z) . stream
603
604 -- | Haskell-style scan
605 scanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
606 {-# INLINE scanl #-}
607 scanl f z = unstream . Stream.scanl f z . stream
608
609 -- | Haskell-style scan with strict accumulator
610 scanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
611 {-# INLINE scanl' #-}
612 scanl' f z = unstream . Stream.scanl' f z . stream
613
614 -- | Scan over a non-empty vector
615 scanl1 :: Vector v a => (a -> a -> a) -> v a -> v a
616 {-# INLINE scanl1 #-}
617 scanl1 f = unstream . inplace (MStream.scanl1 f) . stream
618
619 -- | Scan over a non-empty vector with a strict accumulator
620 scanl1' :: Vector v a => (a -> a -> a) -> v a -> v a
621 {-# INLINE scanl1' #-}
622 scanl1' f = unstream . inplace (MStream.scanl1' f) . stream
623
624 -- Enumeration
625 -- -----------
626
627 -- FIXME: The Enum class is irreparably broken, there just doesn't seem to be a
628 -- way to implement this generically. Either specialise this or define a new
629 -- Enum-like class with a proper interface.
630
631 enumFromTo :: (Vector v a, Enum a) => a -> a -> v a
632 {-# INLINE enumFromTo #-}
633 enumFromTo from to = fromList [from .. to]
634
635 enumFromThenTo :: (Vector v a, Enum a) => a -> a -> a -> v a
636 {-# INLINE enumFromThenTo #-}
637 enumFromThenTo from next to = fromList [from, next .. to]
638
639 -- | Convert a vector to a list
640 toList :: Vector v a => v a -> [a]
641 {-# INLINE toList #-}
642 toList = Stream.toList . stream
643
644 -- | Convert a list to a vector
645 fromList :: Vector v a => [a] -> v a
646 {-# INLINE fromList #-}
647 fromList = unstream . Stream.fromList
648