Simplify null
[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 basicNew :: (forall mv m. MVector mv m a => m (mv a)) -> v a
109
110 -- | Length of the vector (not fusible!)
111 basicLength :: 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 = basicNew (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 = basicLength 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 null #-}
211 null v = length v == 0
212
213 -- Construction
214 -- ------------
215
216 -- | Empty vector
217 empty :: Vector v a => v a
218 {-# INLINE empty #-}
219 empty = unstream Stream.empty
220
221 -- | Vector with exaclty one element
222 singleton :: Vector v a => a -> v a
223 {-# INLINE singleton #-}
224 singleton x = unstream (Stream.singleton x)
225
226 -- | Vector of the given length with the given value in each position
227 replicate :: Vector v a => Int -> a -> v a
228 {-# INLINE replicate #-}
229 replicate n = unstream . Stream.replicate n
230
231 -- | Prepend an element
232 cons :: Vector v a => a -> v a -> v a
233 {-# INLINE cons #-}
234 cons x = unstream . Stream.cons x . stream
235
236 -- | Append an element
237 snoc :: Vector v a => v a -> a -> v a
238 {-# INLINE snoc #-}
239 snoc v = unstream . Stream.snoc (stream v)
240
241 infixr 5 ++
242 -- | Concatenate two vectors
243 (++) :: Vector v a => v a -> v a -> v a
244 {-# INLINE (++) #-}
245 v ++ w = unstream (stream v Stream.++ stream w)
246
247 -- | Create a copy of a vector. Useful when dealing with slices.
248 copy :: Vector v a => v a -> v a
249 {-# INLINE_STREAM copy #-}
250 copy = unstream . stream
251
252 {-# RULES
253
254 "copy/unstream [Vector]" forall v s.
255 copy (new' v (New.unstream s)) = new' v (New.unstream s)
256
257 #-}
258
259 -- Accessing individual elements
260 -- -----------------------------
261
262 -- | Indexing
263 (!) :: Vector v a => v a -> Int -> a
264 {-# INLINE_STREAM (!) #-}
265 v ! i = assert (i >= 0 && i < length v)
266 $ unId (unsafeIndexM v i)
267
268 -- | First element
269 head :: Vector v a => v a -> a
270 {-# INLINE_STREAM head #-}
271 head v = v ! 0
272
273 -- | Last element
274 last :: Vector v a => v a -> a
275 {-# INLINE_STREAM last #-}
276 last v = v ! (length v - 1)
277
278 {-# RULES
279
280 "(!)/unstream [Vector]" forall v i s.
281 new' v (New.unstream s) ! i = s Stream.!! i
282
283 "head/unstream [Vector]" forall v s.
284 head (new' v (New.unstream s)) = Stream.head s
285
286 "last/unstream [Vector]" forall v s.
287 last (new' v (New.unstream s)) = Stream.last s
288
289 #-}
290
291 -- | Monadic indexing which can be strict in the vector while remaining lazy in
292 -- the element.
293 indexM :: (Vector v a, Monad m) => v a -> Int -> m a
294 {-# INLINE_STREAM indexM #-}
295 indexM v i = assert (i >= 0 && i < length v)
296 $ unsafeIndexM v i
297
298 headM :: (Vector v a, Monad m) => v a -> m a
299 {-# INLINE_STREAM headM #-}
300 headM v = indexM v 0
301
302 lastM :: (Vector v a, Monad m) => v a -> m a
303 {-# INLINE_STREAM lastM #-}
304 lastM v = indexM v (length v - 1)
305
306 -- FIXME: the rhs of these rules are lazy in the stream which is WRONG
307 {- RULES
308
309 "indexM/unstream [Vector]" forall v i s.
310 indexM (new' v (New.unstream s)) i = return (s Stream.!! i)
311
312 "headM/unstream [Vector]" forall v s.
313 headM (new' v (New.unstream s)) = return (Stream.head s)
314
315 "lastM/unstream [Vector]" forall v s.
316 lastM (new' v (New.unstream s)) = return (Stream.last s)
317
318 -}
319
320 -- Subarrays
321 -- ---------
322
323 -- FIXME: slicing doesn't work with the inplace stuff at the moment
324
325 -- | Yield a part of the vector without copying it. Safer version of
326 -- 'unsafeSlice'.
327 slice :: Vector v a => v a -> Int -- ^ starting index
328 -> Int -- ^ length
329 -> v a
330 {-# INLINE_STREAM slice #-}
331 slice v i n = assert (i >= 0 && n >= 0 && i+n <= length v)
332 $ unsafeSlice v i n
333
334 -- | Yield all but the last element without copying.
335 init :: Vector v a => v a -> v a
336 {-# INLINE_STREAM init #-}
337 init v = slice v 0 (length v - 1)
338
339 -- | All but the first element (without copying).
340 tail :: Vector v a => v a -> v a
341 {-# INLINE_STREAM tail #-}
342 tail v = slice v 1 (length v - 1)
343
344 -- | Yield the first @n@ elements without copying.
345 take :: Vector v a => Int -> v a -> v a
346 {-# INLINE_STREAM take #-}
347 take n v = slice v 0 (min n' (length v))
348 where n' = max n 0
349
350 -- | Yield all but the first @n@ elements without copying.
351 drop :: Vector v a => Int -> v a -> v a
352 {-# INLINE_STREAM drop #-}
353 drop n v = slice v (min n' len) (max 0 (len - n'))
354 where n' = max n 0
355 len = length v
356
357 {-# RULES
358
359 "slice/new [Vector]" forall v p i n.
360 slice (new' v p) i n = new' v (New.slice p i n)
361
362 "init/new [Vector]" forall v p.
363 init (new' v p) = new' v (New.init p)
364
365 "tail/new [Vector]" forall v p.
366 tail (new' v p) = new' v (New.tail p)
367
368 "take/new [Vector]" forall n v p.
369 take n (new' v p) = new' v (New.take n p)
370
371 "drop/new [Vector]" forall n v p.
372 drop n (new' v p) = new' v (New.drop n p)
373
374 #-}
375
376 -- Permutations
377 -- ------------
378
379 accum :: Vector v a => (a -> b -> a) -> v a -> [(Int,b)] -> v a
380 {-# INLINE accum #-}
381 accum f v us = new (New.accum f (New.unstream (stream v))
382 (Stream.fromList us))
383
384 (//) :: Vector v a => v a -> [(Int, a)] -> v a
385 {-# INLINE (//) #-}
386 v // us = new (New.update (New.unstream (stream v))
387 (Stream.fromList us))
388
389 update :: (Vector v a, Vector v (Int, a)) => v a -> v (Int, a) -> v a
390 {-# INLINE update #-}
391 update v w = new (New.update (New.unstream (stream v)) (stream w))
392
393 -- This somewhat non-intuitive definition ensures that the resulting vector
394 -- does not retain references to the original one even if it is lazy in its
395 -- elements. This would not be the case if we simply used
396 --
397 -- backpermute v is = map (v!) is
398 backpermute :: (Vector v a, Vector v Int) => v a -> v Int -> v a
399 {-# INLINE backpermute #-}
400 backpermute v is = seq v
401 $ unstream
402 $ Stream.unbox
403 $ Stream.map (indexM v)
404 $ stream is
405
406 reverse :: (Vector v a) => v a -> v a
407 {-# INLINE reverse #-}
408 reverse = new . New.reverse . New.unstream . stream
409
410 -- Mapping
411 -- -------
412
413 -- | Map a function over a vector
414 map :: (Vector v a, Vector v b) => (a -> b) -> v a -> v b
415 {-# INLINE map #-}
416 map f = unstream . inplace' (MStream.map f) . stream
417
418 concatMap :: (Vector v a, Vector v b) => (a -> v b) -> v a -> v b
419 {-# INLINE concatMap #-}
420 concatMap f = unstream . Stream.concatMap (stream . f) . stream
421
422 -- Zipping/unzipping
423 -- -----------------
424
425 -- | Zip two vectors with the given function.
426 zipWith :: (Vector v a, Vector v b, Vector v c) => (a -> b -> c) -> v a -> v b -> v c
427 {-# INLINE zipWith #-}
428 zipWith f xs ys = unstream (Stream.zipWith f (stream xs) (stream ys))
429
430 -- | Zip three vectors with the given function.
431 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
432 {-# INLINE zipWith3 #-}
433 zipWith3 f xs ys zs = unstream (Stream.zipWith3 f (stream xs) (stream ys) (stream zs))
434
435 zip :: (Vector v a, Vector v b, Vector v (a,b)) => v a -> v b -> v (a, b)
436 {-# INLINE zip #-}
437 zip = zipWith (,)
438
439 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)
440 {-# INLINE zip3 #-}
441 zip3 = zipWith3 (,,)
442
443 unzip :: (Vector v a, Vector v b, Vector v (a,b)) => v (a, b) -> (v a, v b)
444 {-# INLINE unzip #-}
445 unzip xs = (map fst xs, map snd xs)
446
447 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)
448 {-# INLINE unzip3 #-}
449 unzip3 xs = (map (\(a, b, c) -> a) xs, map (\(a, b, c) -> b) xs, map (\(a, b, c) -> c) xs)
450
451 -- Comparisons
452 -- -----------
453
454 eq :: (Vector v a, Eq a) => v a -> v a -> Bool
455 {-# INLINE eq #-}
456 xs `eq` ys = stream xs == stream ys
457
458 cmp :: (Vector v a, Ord a) => v a -> v a -> Ordering
459 {-# INLINE cmp #-}
460 cmp xs ys = compare (stream xs) (stream ys)
461
462 -- Filtering
463 -- ---------
464
465 -- | Drop elements which do not satisfy the predicate
466 filter :: Vector v a => (a -> Bool) -> v a -> v a
467 {-# INLINE filter #-}
468 filter f = unstream . inplace (MStream.filter f) . stream
469
470 -- | Yield the longest prefix of elements satisfying the predicate.
471 takeWhile :: Vector v a => (a -> Bool) -> v a -> v a
472 {-# INLINE takeWhile #-}
473 takeWhile f = unstream . Stream.takeWhile f . stream
474
475 -- | Drop the longest prefix of elements that satisfy the predicate.
476 dropWhile :: Vector v a => (a -> Bool) -> v a -> v a
477 {-# INLINE dropWhile #-}
478 dropWhile f = unstream . Stream.dropWhile f . stream
479
480 -- Searching
481 -- ---------
482
483 infix 4 `elem`
484 -- | Check whether the vector contains an element
485 elem :: (Vector v a, Eq a) => a -> v a -> Bool
486 {-# INLINE elem #-}
487 elem x = Stream.elem x . stream
488
489 infix 4 `notElem`
490 -- | Inverse of `elem`
491 notElem :: (Vector v a, Eq a) => a -> v a -> Bool
492 {-# INLINE notElem #-}
493 notElem x = Stream.notElem x . stream
494
495 -- | Yield 'Just' the first element matching the predicate or 'Nothing' if no
496 -- such element exists.
497 find :: Vector v a => (a -> Bool) -> v a -> Maybe a
498 {-# INLINE find #-}
499 find f = Stream.find f . stream
500
501 -- | Yield 'Just' the index of the first element matching the predicate or
502 -- 'Nothing' if no such element exists.
503 findIndex :: Vector v a => (a -> Bool) -> v a -> Maybe Int
504 {-# INLINE findIndex #-}
505 findIndex f = Stream.findIndex f . stream
506
507 -- Folding
508 -- -------
509
510 -- | Left fold
511 foldl :: Vector v b => (a -> b -> a) -> a -> v b -> a
512 {-# INLINE foldl #-}
513 foldl f z = Stream.foldl f z . stream
514
515 -- | Lefgt fold on non-empty vectors
516 foldl1 :: Vector v a => (a -> a -> a) -> v a -> a
517 {-# INLINE foldl1 #-}
518 foldl1 f = Stream.foldl1 f . stream
519
520 -- | Left fold with strict accumulator
521 foldl' :: Vector v b => (a -> b -> a) -> a -> v b -> a
522 {-# INLINE foldl' #-}
523 foldl' f z = Stream.foldl' f z . stream
524
525 -- | Left fold on non-empty vectors with strict accumulator
526 foldl1' :: Vector v a => (a -> a -> a) -> v a -> a
527 {-# INLINE foldl1' #-}
528 foldl1' f = Stream.foldl1' f . stream
529
530 -- | Right fold
531 foldr :: Vector v a => (a -> b -> b) -> b -> v a -> b
532 {-# INLINE foldr #-}
533 foldr f z = Stream.foldr f z . stream
534
535 -- | Right fold on non-empty vectors
536 foldr1 :: Vector v a => (a -> a -> a) -> v a -> a
537 {-# INLINE foldr1 #-}
538 foldr1 f = Stream.foldr1 f . stream
539
540 -- Specialised folds
541 -- -----------------
542
543 and :: Vector v Bool => v Bool -> Bool
544 {-# INLINE and #-}
545 and = Stream.and . stream
546
547 or :: Vector v Bool => v Bool -> Bool
548 {-# INLINE or #-}
549 or = Stream.or . stream
550
551 sum :: (Vector v a, Num a) => v a -> a
552 {-# INLINE sum #-}
553 sum = Stream.foldl' (+) 0 . stream
554
555 product :: (Vector v a, Num a) => v a -> a
556 {-# INLINE product #-}
557 product = Stream.foldl' (*) 1 . stream
558
559 maximum :: (Vector v a, Ord a) => v a -> a
560 {-# INLINE maximum #-}
561 maximum = Stream.foldl1' max . stream
562
563 minimum :: (Vector v a, Ord a) => v a -> a
564 {-# INLINE minimum #-}
565 minimum = Stream.foldl1' min . stream
566
567 -- Unfolding
568 -- ---------
569
570 unfoldr :: Vector v a => (b -> Maybe (a, b)) -> b -> v a
571 {-# INLINE unfoldr #-}
572 unfoldr f = unstream . Stream.unfoldr f
573
574 -- Scans
575 -- -----
576
577 -- | Prefix scan
578 prescanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
579 {-# INLINE prescanl #-}
580 prescanl f z = unstream . inplace' (MStream.prescanl f z) . stream
581
582 -- | Prefix scan with strict accumulator
583 prescanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
584 {-# INLINE prescanl' #-}
585 prescanl' f z = unstream . inplace' (MStream.prescanl' f z) . stream
586
587 -- | Suffix scan
588 postscanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
589 {-# INLINE postscanl #-}
590 postscanl f z = unstream . inplace' (MStream.postscanl f z) . stream
591
592 -- | Suffix scan with strict accumulator
593 postscanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
594 {-# INLINE postscanl' #-}
595 postscanl' f z = unstream . inplace' (MStream.postscanl' f z) . stream
596
597 -- | Haskell-style scan
598 scanl :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
599 {-# INLINE scanl #-}
600 scanl f z = unstream . Stream.scanl f z . stream
601
602 -- | Haskell-style scan with strict accumulator
603 scanl' :: (Vector v a, Vector v b) => (a -> b -> a) -> a -> v b -> v a
604 {-# INLINE scanl' #-}
605 scanl' f z = unstream . Stream.scanl' f z . stream
606
607 -- | Scan over a non-empty vector
608 scanl1 :: Vector v a => (a -> a -> a) -> v a -> v a
609 {-# INLINE scanl1 #-}
610 scanl1 f = unstream . inplace (MStream.scanl1 f) . stream
611
612 -- | Scan over a non-empty vector with a strict accumulator
613 scanl1' :: Vector v a => (a -> a -> a) -> v a -> v a
614 {-# INLINE scanl1' #-}
615 scanl1' f = unstream . inplace (MStream.scanl1' f) . stream
616
617 -- Enumeration
618 -- -----------
619
620 -- FIXME: The Enum class is irreparably broken, there just doesn't seem to be a
621 -- way to implement this generically. Either specialise this or define a new
622 -- Enum-like class with a proper interface.
623
624 enumFromTo :: (Vector v a, Enum a) => a -> a -> v a
625 {-# INLINE enumFromTo #-}
626 enumFromTo x y = unstream (Stream.enumFromTo x y)
627
628 enumFromThenTo :: (Vector v a, Enum a) => a -> a -> a -> v a
629 {-# INLINE enumFromThenTo #-}
630 enumFromThenTo from next to = fromList [from, next .. to]
631
632 -- | Convert a vector to a list
633 toList :: Vector v a => v a -> [a]
634 {-# INLINE toList #-}
635 toList = Stream.toList . stream
636
637 -- | Convert a list to a vector
638 fromList :: Vector v a => [a] -> v a
639 {-# INLINE fromList #-}
640 fromList = unstream . Stream.fromList
641