Slight optimisation
[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 $ MStream.trans (Id . unBox)
410 $ MStream.mapM (indexM v)
411 $ MStream.trans (Box . unId)
412 $ stream is
413
414 reverse :: (Vector v a) => v a -> v a
415 {-# INLINE reverse #-}
416 reverse = new . New.reverse . New.unstream . stream
417
418 -- Mapping
419 -- -------
420
421 -- | Map a function over a vector
422 map :: (Vector v a, Vector v b) => (a -> b) -> v a -> v b
423 {-# INLINE map #-}
424 map f = unstream . inplace' (MStream.map f) . stream
425
426 concatMap :: (Vector v a, Vector v b) => (a -> v b) -> v a -> v b
427 {-# INLINE concatMap #-}
428 concatMap f = unstream . Stream.concatMap (stream . f) . stream
429
430 -- Zipping/unzipping
431 -- -----------------
432
433 -- | Zip two vectors with the given function.
434 zipWith :: (Vector v a, Vector v b, Vector v c) => (a -> b -> c) -> v a -> v b -> v c
435 {-# INLINE zipWith #-}
436 zipWith f xs ys = unstream (Stream.zipWith f (stream xs) (stream ys))
437
438 -- | Zip three vectors with the given function.
439 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
440 {-# INLINE zipWith3 #-}
441 zipWith3 f xs ys zs = unstream (Stream.zipWith3 f (stream xs) (stream ys) (stream zs))
442
443 zip :: (Vector v a, Vector v b, Vector v (a,b)) => v a -> v b -> v (a, b)
444 {-# INLINE zip #-}
445 zip = zipWith (,)
446
447 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)
448 {-# INLINE zip3 #-}
449 zip3 = zipWith3 (,,)
450
451 unzip :: (Vector v a, Vector v b, Vector v (a,b)) => v (a, b) -> (v a, v b)
452 {-# INLINE unzip #-}
453 unzip xs = (map fst xs, map snd xs)
454
455 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)
456 {-# INLINE unzip3 #-}
457 unzip3 xs = (map (\(a, b, c) -> a) xs, map (\(a, b, c) -> b) xs, map (\(a, b, c) -> c) xs)
458
459 -- Comparisons
460 -- -----------
461
462 eq :: (Vector v a, Eq a) => v a -> v a -> Bool
463 {-# INLINE eq #-}
464 xs `eq` ys = stream xs == stream ys
465
466 cmp :: (Vector v a, Ord a) => v a -> v a -> Ordering
467 {-# INLINE cmp #-}
468 cmp xs ys = compare (stream xs) (stream ys)
469
470 -- Filtering
471 -- ---------
472
473 -- | Drop elements which do not satisfy the predicate
474 filter :: Vector v a => (a -> Bool) -> v a -> v a
475 {-# INLINE filter #-}
476 filter f = unstream . inplace (MStream.filter f) . stream
477
478 -- | Yield the longest prefix of elements satisfying the predicate.
479 takeWhile :: Vector v a => (a -> Bool) -> v a -> v a
480 {-# INLINE takeWhile #-}
481 takeWhile f = unstream . Stream.takeWhile f . stream
482
483 -- | Drop the longest prefix of elements that satisfy the predicate.
484 dropWhile :: Vector v a => (a -> Bool) -> v a -> v a
485 {-# INLINE dropWhile #-}
486 dropWhile f = unstream . Stream.dropWhile f . stream
487
488 -- Searching
489 -- ---------
490
491 infix 4 `elem`
492 -- | Check whether the vector contains an element
493 elem :: (Vector v a, Eq a) => a -> v a -> Bool
494 {-# INLINE elem #-}
495 elem x = Stream.elem x . stream
496
497 infix 4 `notElem`
498 -- | Inverse of `elem`
499 notElem :: (Vector v a, Eq a) => a -> v a -> Bool
500 {-# INLINE notElem #-}
501 notElem x = Stream.notElem x . stream
502
503 -- | Yield 'Just' the first element matching the predicate or 'Nothing' if no
504 -- such element exists.
505 find :: Vector v a => (a -> Bool) -> v a -> Maybe a
506 {-# INLINE find #-}
507 find f = Stream.find f . stream
508
509 -- | Yield 'Just' the index of the first element matching the predicate or
510 -- 'Nothing' if no such element exists.
511 findIndex :: Vector v a => (a -> Bool) -> v a -> Maybe Int
512 {-# INLINE findIndex #-}
513 findIndex f = Stream.findIndex f . stream
514
515 -- Folding
516 -- -------
517
518 -- | Left fold
519 foldl :: Vector v b => (a -> b -> a) -> a -> v b -> a
520 {-# INLINE foldl #-}
521 foldl f z = Stream.foldl f z . stream
522
523 -- | Lefgt fold on non-empty vectors
524 foldl1 :: Vector v a => (a -> a -> a) -> v a -> a
525 {-# INLINE foldl1 #-}
526 foldl1 f = Stream.foldl1 f . stream
527
528 -- | Left fold with strict accumulator
529 foldl' :: Vector v b => (a -> b -> a) -> a -> v b -> a
530 {-# INLINE foldl' #-}
531 foldl' f z = Stream.foldl' f z . stream
532
533 -- | Left fold on non-empty vectors with strict accumulator
534 foldl1' :: Vector v a => (a -> a -> a) -> v a -> a
535 {-# INLINE foldl1' #-}
536 foldl1' f = Stream.foldl1' f . stream
537
538 -- | Right fold
539 foldr :: Vector v a => (a -> b -> b) -> b -> v a -> b
540 {-# INLINE foldr #-}
541 foldr f z = Stream.foldr f z . stream
542
543 -- | Right fold on non-empty vectors
544 foldr1 :: Vector v a => (a -> a -> a) -> v a -> a
545 {-# INLINE foldr1 #-}
546 foldr1 f = Stream.foldr1 f . stream
547
548 -- Specialised folds
549 -- -----------------
550
551 and :: Vector v Bool => v Bool -> Bool
552 {-# INLINE and #-}
553 and = Stream.and . stream
554
555 or :: Vector v Bool => v Bool -> Bool
556 {-# INLINE or #-}
557 or = Stream.or . stream
558
559 sum :: (Vector v a, Num a) => v a -> a
560 {-# INLINE sum #-}
561 sum = Stream.foldl' (+) 0 . stream
562
563 product :: (Vector v a, Num a) => v a -> a
564 {-# INLINE product #-}
565 product = Stream.foldl' (*) 1 . stream
566
567 maximum :: (Vector v a, Ord a) => v a -> a
568 {-# INLINE maximum #-}
569 maximum = Stream.foldl1' max . stream
570
571 minimum :: (Vector v a, Ord a) => v a -> a
572 {-# INLINE minimum #-}
573 minimum = Stream.foldl1' min . stream
574
575 -- Unfolding
576 -- ---------
577
578 unfoldr :: Vector v a => (b -> Maybe (a, b)) -> b -> v a
579 {-# INLINE unfoldr #-}
580 unfoldr f = unstream . Stream.unfoldr f
581
582 -- Scans
583 -- -----
584
585 -- | Prefix scan
586 prescanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
587 {-# INLINE prescanl #-}
588 prescanl f z = unstream . inplace' (MStream.prescanl f z) . stream
589
590 -- | Prefix scan with strict accumulator
591 prescanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
592 {-# INLINE prescanl' #-}
593 prescanl' f z = unstream . inplace' (MStream.prescanl' f z) . stream
594
595 -- | Suffix scan
596 postscanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
597 {-# INLINE postscanl #-}
598 postscanl f z = unstream . inplace' (MStream.postscanl f z) . stream
599
600 -- | Suffix scan with strict accumulator
601 postscanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
602 {-# INLINE postscanl' #-}
603 postscanl' f z = unstream . inplace' (MStream.postscanl' f z) . stream
604
605 -- | Haskell-style scan
606 scanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
607 {-# INLINE scanl #-}
608 scanl f z = unstream . Stream.scanl f z . stream
609
610 -- | Haskell-style scan with strict accumulator
611 scanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
612 {-# INLINE scanl' #-}
613 scanl' f z = unstream . Stream.scanl' f z . stream
614
615 -- | Scan over a non-empty vector
616 scanl1 :: Vector v a => (a -> a -> a) -> v a -> v a
617 {-# INLINE scanl1 #-}
618 scanl1 f = unstream . inplace (MStream.scanl1 f) . stream
619
620 -- | Scan over a non-empty vector with a strict accumulator
621 scanl1' :: Vector v a => (a -> a -> a) -> v a -> v a
622 {-# INLINE scanl1' #-}
623 scanl1' f = unstream . inplace (MStream.scanl1' f) . stream
624
625 -- Enumeration
626 -- -----------
627
628 -- FIXME: The Enum class is irreparably broken, there just doesn't seem to be a
629 -- way to implement this generically. Either specialise this or define a new
630 -- Enum-like class with a proper interface.
631
632 enumFromTo :: (Vector v a, Enum a) => a -> a -> v a
633 {-# INLINE enumFromTo #-}
634 enumFromTo from to = fromList [from .. to]
635
636 enumFromThenTo :: (Vector v a, Enum a) => a -> a -> a -> v a
637 {-# INLINE enumFromThenTo #-}
638 enumFromThenTo from next to = fromList [from, next .. to]
639
640 -- | Convert a vector to a list
641 toList :: Vector v a => v a -> [a]
642 {-# INLINE toList #-}
643 toList = Stream.toList . stream
644
645 -- | Convert a list to a vector
646 fromList :: Vector v a => [a] -> v a
647 {-# INLINE fromList #-}
648 fromList = unstream . Stream.fromList
649