cd2f03b297ae79bbd6b8df8cb5745fe6a5f7b3f9
[haskell-directory.git] / GHC / PArr.hs
1 {-# OPTIONS_GHC -fparr -funbox-strict-fields #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.PArr
6 -- Copyright   :  (c) 2001-2002 Manuel M T Chakravarty & Gabriele Keller
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  Manuel M. T. Chakravarty <chak@cse.unsw.edu.au>
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 --  Basic implementation of Parallel Arrays.
14 --
15 --  This module has two functions: (1) It defines the interface to the
16 --  parallel array extension of the Prelude and (2) it provides a vanilla
17 --  implementation of parallel arrays that does not require to flatten the
18 --  array code.  The implementation is not very optimised.
19 --
20 --- DOCU ----------------------------------------------------------------------
21 --
22 --  Language: Haskell 98 plus unboxed values and parallel arrays
23 --
24 --  The semantic difference between standard Haskell arrays (aka "lazy
25 --  arrays") and parallel arrays (aka "strict arrays") is that the evaluation
26 --  of two different elements of a lazy array is independent, whereas in a
27 --  strict array either non or all elements are evaluated.  In other words,
28 --  when a parallel array is evaluated to WHNF, all its elements will be
29 --  evaluated to WHNF.  The name parallel array indicates that all array
30 --  elements may, in general, be evaluated to WHNF in parallel without any
31 --  need to resort to speculative evaluation.  This parallel evaluation
32 --  semantics is also beneficial in the sequential case, as it facilitates
33 --  loop-based array processing as known from classic array-based languages,
34 --  such as Fortran.
35 --
36 --  The interface of this module is essentially a variant of the list
37 --  component of the Prelude, but also includes some functions (such as
38 --  permutations) that are not provided for lists.  The following list
39 --  operations are not supported on parallel arrays, as they would require the
40 --  availability of infinite parallel arrays: `iterate', `repeat', and `cycle'.
41 --
42 --  The current implementation is quite simple and entirely based on boxed
43 --  arrays.  One disadvantage of boxed arrays is that they require to
44 --  immediately initialise all newly allocated arrays with an error thunk to
45 --  keep the garbage collector happy, even if it is guaranteed that the array
46 --  is fully initialised with different values before passing over the
47 --  user-visible interface boundary.  Currently, no effort is made to use
48 --  raw memory copy operations to speed things up.
49 --
50 --- TODO ----------------------------------------------------------------------
51 --
52 --  * We probably want a standard library `PArray' in addition to the prelude
53 --    extension in the same way as the standard library `List' complements the
54 --    list functions from the prelude.
55 --
56 --  * Currently, functions that emphasis the constructor-based definition of
57 --    lists (such as, head, last, tail, and init) are not supported.  
58 --
59 --    Is it worthwhile to support the string processing functions lines,
60 --    words, unlines, and unwords?  (Currently, they are not implemented.)
61 --
62 --    It can, however, be argued that it would be worthwhile to include them
63 --    for completeness' sake; maybe only in the standard library `PArray'.
64 --
65 --  * Prescans are often more useful for array programming than scans.  Shall
66 --    we include them into the Prelude or the library?
67 --
68 --  * Due to the use of the iterator `loop', we could define some fusion rules
69 --    in this module.
70 --
71 --  * We might want to add bounds checks that can be deactivated.
72 --
73
74 module GHC.PArr (
75   -- [::],              -- Built-in syntax
76
77   mapP,                 -- :: (a -> b) -> [:a:] -> [:b:]
78   (+:+),                -- :: [:a:] -> [:a:] -> [:a:]
79   filterP,              -- :: (a -> Bool) -> [:a:] -> [:a:]
80   concatP,              -- :: [:[:a:]:] -> [:a:]
81   concatMapP,           -- :: (a -> [:b:]) -> [:a:] -> [:b:]
82 --  head, last, tail, init,   -- it's not wise to use them on arrays
83   nullP,                -- :: [:a:] -> Bool
84   lengthP,              -- :: [:a:] -> Int
85   (!:),                 -- :: [:a:] -> Int -> a
86   foldlP,               -- :: (a -> b -> a) -> a -> [:b:] -> a
87   foldl1P,              -- :: (a -> a -> a) ->      [:a:] -> a
88   scanlP,               -- :: (a -> b -> a) -> a -> [:b:] -> [:a:]
89   scanl1P,              -- :: (a -> a -> a) ->      [:a:] -> [:a:]
90   foldrP,               -- :: (a -> b -> b) -> b -> [:a:] -> b
91   foldr1P,              -- :: (a -> a -> a) ->      [:a:] -> a
92   scanrP,               -- :: (a -> b -> b) -> b -> [:a:] -> [:b:]
93   scanr1P,              -- :: (a -> a -> a) ->      [:a:] -> [:a:]
94 --  iterate, repeat,          -- parallel arrays must be finite
95   replicateP,           -- :: Int -> a -> [:a:]
96 --  cycle,                    -- parallel arrays must be finite
97   takeP,                -- :: Int -> [:a:] -> [:a:]
98   dropP,                -- :: Int -> [:a:] -> [:a:]
99   splitAtP,             -- :: Int -> [:a:] -> ([:a:],[:a:])
100   takeWhileP,           -- :: (a -> Bool) -> [:a:] -> [:a:]
101   dropWhileP,           -- :: (a -> Bool) -> [:a:] -> [:a:]
102   spanP,                -- :: (a -> Bool) -> [:a:] -> ([:a:], [:a:])
103   breakP,               -- :: (a -> Bool) -> [:a:] -> ([:a:], [:a:])
104 --  lines, words, unlines, unwords,  -- is string processing really needed
105   reverseP,             -- :: [:a:] -> [:a:]
106   andP,                 -- :: [:Bool:] -> Bool
107   orP,                  -- :: [:Bool:] -> Bool
108   anyP,                 -- :: (a -> Bool) -> [:a:] -> Bool
109   allP,                 -- :: (a -> Bool) -> [:a:] -> Bool
110   elemP,                -- :: (Eq a) => a -> [:a:] -> Bool
111   notElemP,             -- :: (Eq a) => a -> [:a:] -> Bool
112   lookupP,              -- :: (Eq a) => a -> [:(a, b):] -> Maybe b
113   sumP,                 -- :: (Num a) => [:a:] -> a
114   productP,             -- :: (Num a) => [:a:] -> a
115   maximumP,             -- :: (Ord a) => [:a:] -> a
116   minimumP,             -- :: (Ord a) => [:a:] -> a
117   zipP,                 -- :: [:a:] -> [:b:]          -> [:(a, b)   :]
118   zip3P,                -- :: [:a:] -> [:b:] -> [:c:] -> [:(a, b, c):]
119   zipWithP,             -- :: (a -> b -> c)      -> [:a:] -> [:b:] -> [:c:]
120   zipWith3P,            -- :: (a -> b -> c -> d) -> [:a:]->[:b:]->[:c:]->[:d:]
121   unzipP,               -- :: [:(a, b)   :] -> ([:a:], [:b:])
122   unzip3P,              -- :: [:(a, b, c):] -> ([:a:], [:b:], [:c:])
123
124   -- overloaded functions
125   --
126   enumFromToP,          -- :: Enum a => a -> a      -> [:a:]
127   enumFromThenToP,      -- :: Enum a => a -> a -> a -> [:a:]
128
129   -- the following functions are not available on lists
130   --
131   toP,                  -- :: [a] -> [:a:]
132   fromP,                -- :: [:a:] -> [a]
133   sliceP,               -- :: Int -> Int -> [:e:] -> [:e:]
134   foldP,                -- :: (e -> e -> e) -> e -> [:e:] -> e
135   fold1P,               -- :: (e -> e -> e) ->      [:e:] -> e
136   permuteP,             -- :: [:Int:] -> [:e:] ->          [:e:]
137   bpermuteP,            -- :: [:Int:] -> [:e:] ->          [:e:]
138   dpermuteP,            -- :: [:Int:] -> [:e:] -> [:e:] -> [:e:]
139   crossP,               -- :: [:a:] -> [:b:] -> [:(a, b):]
140   crossMapP,            -- :: [:a:] -> (a -> [:b:]) -> [:(a, b):]
141   indexOfP              -- :: (a -> Bool) -> [:a:] -> [:Int:]
142 ) where
143
144 #ifndef __HADDOCK__
145
146 import Prelude
147
148 import GHC.ST   ( ST(..), STRep, runST )
149 import GHC.Exts ( Int#, Array#, Int(I#), MutableArray#, newArray#,
150                   unsafeFreezeArray#, indexArray#, writeArray#, (<#), (>=#) )
151
152 infixl 9  !:
153 infixr 5  +:+
154 infix  4  `elemP`, `notElemP`
155
156
157 -- representation of parallel arrays
158 -- ---------------------------------
159
160 -- this rather straight forward implementation maps parallel arrays to the
161 -- internal representation used for standard Haskell arrays in GHC's Prelude
162 -- (EXPORTED ABSTRACTLY)
163 --
164 -- * This definition *must* be kept in sync with `TysWiredIn.parrTyCon'!
165 --
166 data [::] e = PArr Int# (Array# e)
167
168
169 -- exported operations on parallel arrays
170 -- --------------------------------------
171
172 -- operations corresponding to list operations
173 --
174
175 mapP   :: (a -> b) -> [:a:] -> [:b:]
176 mapP f  = fst . loop (mapEFL f) noAL
177
178 (+:+)     :: [:a:] -> [:a:] -> [:a:]
179 a1 +:+ a2  = fst $ loop (mapEFL sel) noAL (enumFromToP 0 (len1 + len2 - 1))
180                        -- we can't use the [:x..y:] form here for tedious
181                        -- reasons to do with the typechecker and the fact that
182                        -- `enumFromToP' is defined in the same module
183              where
184                len1 = lengthP a1
185                len2 = lengthP a2
186                --
187                sel i | i < len1  = a1!:i
188                      | otherwise = a2!:(i - len1)
189
190 filterP   :: (a -> Bool) -> [:a:] -> [:a:]
191 filterP p  = fst . loop (filterEFL p) noAL
192
193 concatP     :: [:[:a:]:] -> [:a:]
194 concatP xss  = foldlP (+:+) [::] xss
195
196 concatMapP   :: (a -> [:b:]) -> [:a:] -> [:b:]
197 concatMapP f  = concatP . mapP f
198
199 --  head, last, tail, init,   -- it's not wise to use them on arrays
200
201 nullP      :: [:a:] -> Bool
202 nullP [::]  = True
203 nullP _     = False
204
205 lengthP             :: [:a:] -> Int
206 lengthP (PArr n# _)  = I# n#
207
208 (!:) :: [:a:] -> Int -> a
209 (!:)  = indexPArr
210
211 foldlP     :: (a -> b -> a) -> a -> [:b:] -> a
212 foldlP f z  = snd . loop (foldEFL (flip f)) z
213
214 foldl1P        :: (a -> a -> a) -> [:a:] -> a
215 foldl1P f [::]  = error "Prelude.foldl1P: empty array"
216 foldl1P f a     = snd $ loopFromTo 1 (lengthP a - 1) (foldEFL f) (a!:0) a
217
218 scanlP     :: (a -> b -> a) -> a -> [:b:] -> [:a:]
219 scanlP f z  = fst . loop (scanEFL (flip f)) z
220
221 scanl1P        :: (a -> a -> a) -> [:a:] -> [:a:]
222 scanl1P f [::]  = error "Prelude.scanl1P: empty array"
223 scanl1P f a     = fst $ loopFromTo 1 (lengthP a - 1) (scanEFL f) (a!:0) a
224
225 foldrP :: (a -> b -> b) -> b -> [:a:] -> b
226 foldrP  = error "Prelude.foldrP: not implemented yet" -- FIXME
227
228 foldr1P :: (a -> a -> a) -> [:a:] -> a
229 foldr1P  = error "Prelude.foldr1P: not implemented yet" -- FIXME
230
231 scanrP :: (a -> b -> b) -> b -> [:a:] -> [:b:]
232 scanrP  = error "Prelude.scanrP: not implemented yet" -- FIXME
233
234 scanr1P :: (a -> a -> a) -> [:a:] -> [:a:]
235 scanr1P  = error "Prelude.scanr1P: not implemented yet" -- FIXME
236
237 --  iterate, repeat           -- parallel arrays must be finite
238
239 replicateP             :: Int -> a -> [:a:]
240 {-# INLINE replicateP #-}
241 replicateP n e  = runST (do
242   marr# <- newArray n e
243   mkPArr n marr#)
244
245 --  cycle                     -- parallel arrays must be finite
246
247 takeP   :: Int -> [:a:] -> [:a:]
248 takeP n  = sliceP 0 (n - 1)
249
250 dropP     :: Int -> [:a:] -> [:a:]
251 dropP n a  = sliceP n (lengthP a - 1) a
252
253 splitAtP      :: Int -> [:a:] -> ([:a:],[:a:])
254 splitAtP n xs  = (takeP n xs, dropP n xs)
255
256 takeWhileP :: (a -> Bool) -> [:a:] -> [:a:]
257 takeWhileP  = error "Prelude.takeWhileP: not implemented yet" -- FIXME
258
259 dropWhileP :: (a -> Bool) -> [:a:] -> [:a:]
260 dropWhileP  = error "Prelude.dropWhileP: not implemented yet" -- FIXME
261
262 spanP :: (a -> Bool) -> [:a:] -> ([:a:], [:a:])
263 spanP  = error "Prelude.spanP: not implemented yet" -- FIXME
264
265 breakP   :: (a -> Bool) -> [:a:] -> ([:a:], [:a:])
266 breakP p  = spanP (not . p)
267
268 --  lines, words, unlines, unwords,  -- is string processing really needed
269
270 reverseP   :: [:a:] -> [:a:]
271 reverseP a  = permuteP (enumFromThenToP (len - 1) (len - 2) 0) a
272                        -- we can't use the [:x, y..z:] form here for tedious
273                        -- reasons to do with the typechecker and the fact that
274                        -- `enumFromThenToP' is defined in the same module
275               where
276                 len = lengthP a
277
278 andP :: [:Bool:] -> Bool
279 andP  = foldP (&&) True
280
281 orP :: [:Bool:] -> Bool
282 orP  = foldP (||) True
283
284 anyP   :: (a -> Bool) -> [:a:] -> Bool
285 anyP p  = orP . mapP p
286
287 allP :: (a -> Bool) -> [:a:] -> Bool
288 allP p  = andP . mapP p
289
290 elemP   :: (Eq a) => a -> [:a:] -> Bool
291 elemP x  = anyP (== x)
292
293 notElemP   :: (Eq a) => a -> [:a:] -> Bool
294 notElemP x  = allP (/= x)
295
296 lookupP :: (Eq a) => a -> [:(a, b):] -> Maybe b
297 lookupP  = error "Prelude.lookupP: not implemented yet" -- FIXME
298
299 sumP :: (Num a) => [:a:] -> a
300 sumP  = foldP (+) 0
301
302 productP :: (Num a) => [:a:] -> a
303 productP  = foldP (*) 1
304
305 maximumP      :: (Ord a) => [:a:] -> a
306 maximumP [::]  = error "Prelude.maximumP: empty parallel array"
307 maximumP xs    = fold1P max xs
308
309 minimumP :: (Ord a) => [:a:] -> a
310 minimumP [::]  = error "Prelude.minimumP: empty parallel array"
311 minimumP xs    = fold1P min xs
312
313 zipP :: [:a:] -> [:b:] -> [:(a, b):]
314 zipP  = zipWithP (,)
315
316 zip3P :: [:a:] -> [:b:] -> [:c:] -> [:(a, b, c):]
317 zip3P  = zipWith3P (,,)
318
319 zipWithP         :: (a -> b -> c) -> [:a:] -> [:b:] -> [:c:]
320 zipWithP f a1 a2  = let 
321                       len1 = lengthP a1
322                       len2 = lengthP a2
323                       len  = len1 `min` len2
324                     in
325                     fst $ loopFromTo 0 (len - 1) combine 0 a1
326                     where
327                       combine e1 i = (Just $ f e1 (a2!:i), i + 1)
328
329 zipWith3P :: (a -> b -> c -> d) -> [:a:]->[:b:]->[:c:]->[:d:]
330 zipWith3P f a1 a2 a3 = let 
331                         len1 = lengthP a1
332                         len2 = lengthP a2
333                         len3 = lengthP a3
334                         len  = len1 `min` len2 `min` len3
335                       in
336                       fst $ loopFromTo 0 (len - 1) combine 0 a1
337                       where
338                         combine e1 i = (Just $ f e1 (a2!:i) (a3!:i), i + 1)
339
340 unzipP   :: [:(a, b):] -> ([:a:], [:b:])
341 unzipP a  = (fst $ loop (mapEFL fst) noAL a, fst $ loop (mapEFL snd) noAL a)
342 -- FIXME: these two functions should be optimised using a tupled custom loop
343 unzip3P   :: [:(a, b, c):] -> ([:a:], [:b:], [:c:])
344 unzip3P a  = (fst $ loop (mapEFL fst3) noAL a, 
345               fst $ loop (mapEFL snd3) noAL a,
346               fst $ loop (mapEFL trd3) noAL a)
347              where
348                fst3 (a, _, _) = a
349                snd3 (_, b, _) = b
350                trd3 (_, _, c) = c
351
352 -- instances
353 --
354
355 instance Eq a => Eq [:a:] where
356   a1 == a2 | lengthP a1 == lengthP a2 = andP (zipWithP (==) a1 a2)
357            | otherwise                = False
358
359 instance Ord a => Ord [:a:] where
360   compare a1 a2 = case foldlP combineOrdering EQ (zipWithP compare a1 a2) of
361                     EQ | lengthP a1 == lengthP a2 -> EQ
362                        | lengthP a1 <  lengthP a2 -> LT
363                        | otherwise                -> GT
364                   where
365                     combineOrdering EQ    EQ    = EQ
366                     combineOrdering EQ    other = other
367                     combineOrdering other _     = other
368
369 instance Functor [::] where
370   fmap = mapP
371
372 instance Monad [::] where
373   m >>= k  = foldrP ((+:+) . k      ) [::] m
374   m >>  k  = foldrP ((+:+) . const k) [::] m
375   return x = [:x:]
376   fail _   = [::]
377
378 instance Show a => Show [:a:]  where
379   showsPrec _  = showPArr . fromP
380     where
381       showPArr []     s = "[::]" ++ s
382       showPArr (x:xs) s = "[:" ++ shows x (showPArr' xs s)
383
384       showPArr' []     s = ":]" ++ s
385       showPArr' (y:ys) s = ',' : shows y (showPArr' ys s)
386
387 instance Read a => Read [:a:]  where
388   readsPrec _ a = [(toP v, rest) | (v, rest) <- readPArr a]
389     where
390       readPArr = readParen False (\r -> do
391                                           ("[:",s) <- lex r
392                                           readPArr1 s)
393       readPArr1 s = 
394         (do { (":]", t) <- lex s; return ([], t) }) ++
395         (do { (x, t) <- reads s; (xs, u) <- readPArr2 t; return (x:xs, u) })
396
397       readPArr2 s = 
398         (do { (":]", t) <- lex s; return ([], t) }) ++
399         (do { (",", t) <- lex s; (x, u) <- reads t; (xs, v) <- readPArr2 u; 
400               return (x:xs, v) })
401
402 -- overloaded functions
403 -- 
404
405 -- Ideally, we would like `enumFromToP' and `enumFromThenToP' to be members of
406 -- `Enum'.  On the other hand, we really do not want to change `Enum'.  Thus,
407 -- for the moment, we hope that the compiler is sufficiently clever to
408 -- properly fuse the following definitions.
409
410 enumFromToP     :: Enum a => a -> a -> [:a:]
411 enumFromToP x y  = mapP toEnum (eftInt (fromEnum x) (fromEnum y))
412   where
413     eftInt x y = scanlP (+) x $ replicateP (y - x + 1) 1
414
415 enumFromThenToP       :: Enum a => a -> a -> a -> [:a:]
416 enumFromThenToP x y z  = 
417   mapP toEnum (efttInt (fromEnum x) (fromEnum y) (fromEnum z))
418   where
419     efttInt x y z = scanlP (+) x $ 
420                       replicateP (abs (z - x) `div` abs delta + 1) delta
421       where
422        delta = y - x
423
424 -- the following functions are not available on lists
425 --
426
427 -- create an array from a list (EXPORTED)
428 --
429 toP   :: [a] -> [:a:]
430 toP l  = fst $ loop store l (replicateP (length l) ())
431          where
432            store _ (x:xs) = (Just x, xs)
433
434 -- convert an array to a list (EXPORTED)
435 --
436 fromP   :: [:a:] -> [a]
437 fromP a  = [a!:i | i <- [0..lengthP a - 1]]
438
439 -- cut a subarray out of an array (EXPORTED)
440 --
441 sliceP :: Int -> Int -> [:e:] -> [:e:]
442 sliceP from to a = 
443   fst $ loopFromTo (0 `max` from) (to `min` (lengthP a - 1)) (mapEFL id) noAL a
444
445 -- parallel folding (EXPORTED)
446 --
447 -- * the first argument must be associative; otherwise, the result is undefined
448 --
449 foldP :: (e -> e -> e) -> e -> [:e:] -> e
450 foldP  = foldlP
451
452 -- parallel folding without explicit neutral (EXPORTED)
453 --
454 -- * the first argument must be associative; otherwise, the result is undefined
455 --
456 fold1P :: (e -> e -> e) -> [:e:] -> e
457 fold1P  = foldl1P
458
459 -- permute an array according to the permutation vector in the first argument
460 -- (EXPORTED)
461 --
462 permuteP       :: [:Int:] -> [:e:] -> [:e:]
463 permuteP is es 
464   | isLen /= esLen = error "GHC.PArr: arguments must be of the same length"
465   | otherwise      = runST (do
466                        marr <- newArray isLen noElem
467                        permute marr is es
468                        mkPArr isLen marr)
469   where
470     noElem = error "GHC.PArr.permuteP: I do not exist!"
471              -- unlike standard Haskell arrays, this value represents an
472              -- internal error
473     isLen = lengthP is
474     esLen = lengthP es
475
476 -- permute an array according to the back-permutation vector in the first
477 -- argument (EXPORTED)
478 --
479 -- * the permutation vector must represent a surjective function; otherwise,
480 --   the result is undefined
481 --
482 bpermuteP       :: [:Int:] -> [:e:] -> [:e:]
483 bpermuteP is es  = fst $ loop (mapEFL (es!:)) noAL is
484
485 -- permute an array according to the permutation vector in the first
486 -- argument, which need not be surjective (EXPORTED)
487 --
488 -- * any elements in the result that are not covered by the permutation
489 --   vector assume the value of the corresponding position of the third
490 --   argument 
491 --
492 dpermuteP :: [:Int:] -> [:e:] -> [:e:] -> [:e:]
493 dpermuteP is es dft
494   | isLen /= esLen = error "GHC.PArr: arguments must be of the same length"
495   | otherwise      = runST (do
496                        marr <- newArray dftLen noElem
497                        trans 0 (isLen - 1) marr dft copyOne noAL
498                        permute marr is es
499                        mkPArr dftLen marr)
500   where
501     noElem = error "GHC.PArr.permuteP: I do not exist!"
502              -- unlike standard Haskell arrays, this value represents an
503              -- internal error
504     isLen  = lengthP is
505     esLen  = lengthP es
506     dftLen = lengthP dft
507
508     copyOne e _ = (Just e, noAL)
509
510 -- computes the cross combination of two arrays (EXPORTED)
511 --
512 crossP       :: [:a:] -> [:b:] -> [:(a, b):]
513 crossP a1 a2  = fst $ loop combine (0, 0) $ replicateP len ()
514                 where
515                   len1 = lengthP a1
516                   len2 = lengthP a2
517                   len  = len1 * len2
518                   --
519                   combine _ (i, j) = (Just $ (a1!:i, a2!:j), next)
520                                      where
521                                        next | (i + 1) == len1 = (0    , j + 1)
522                                             | otherwise       = (i + 1, j)
523
524 {- An alternative implementation
525    * The one above is certainly better for flattened code, but here where we
526      are handling boxed arrays, the trade off is less clear.  However, I
527      think, the above one is still better.
528
529 crossP a1 a2  = let
530                   len1 = lengthP a1
531                   len2 = lengthP a2
532                   x1   = concatP $ mapP (replicateP len2) a1
533                   x2   = concatP $ replicateP len1 a2
534                 in
535                 zipP x1 x2
536  -}
537
538 -- |Compute a cross of an array and the arrays produced by the given function
539 -- for the elements of the first array.
540 --
541 crossMapP :: [:a:] -> (a -> [:b:]) -> [:(a, b):]
542 crossMapP a f = let
543                   bs   = mapP f a
544                   segd = mapP lengthP bs
545                   as   = zipWithP replicateP segd a
546                 in
547                 zipP (concatP as) (concatP bs)
548
549 {- The following may seem more straight forward, but the above is very cheap
550    with segmented arrays, as `mapP lengthP', `zipP', and `concatP' are
551    constant time, and `map f' uses the lifted version of `f'.
552
553 crossMapP a f = concatP $ mapP (\x -> mapP ((,) x) (f x)) a
554
555  -}
556
557 -- computes an index array for all elements of the second argument for which
558 -- the predicate yields `True' (EXPORTED)
559 --
560 indexOfP     :: (a -> Bool) -> [:a:] -> [:Int:]
561 indexOfP p a  = fst $ loop calcIdx 0 a
562                 where
563                   calcIdx e idx | p e       = (Just idx, idx + 1)
564                                 | otherwise = (Nothing , idx    )
565
566
567 -- auxiliary functions
568 -- -------------------
569
570 -- internally used mutable boxed arrays
571 --
572 data MPArr s e = MPArr Int# (MutableArray# s e)
573
574 -- allocate a new mutable array that is pre-initialised with a given value
575 --
576 newArray             :: Int -> e -> ST s (MPArr s e)
577 {-# INLINE newArray #-}
578 newArray (I# n#) e  = ST $ \s1# ->
579   case newArray# n# e s1# of { (# s2#, marr# #) ->
580   (# s2#, MPArr n# marr# #)}
581
582 -- convert a mutable array into the external parallel array representation
583 --
584 mkPArr                           :: Int -> MPArr s e -> ST s [:e:]
585 {-# INLINE mkPArr #-}
586 mkPArr (I# n#) (MPArr _ marr#)  = ST $ \s1# ->
587   case unsafeFreezeArray# marr# s1#   of { (# s2#, arr# #) ->
588   (# s2#, PArr n# arr# #) }
589
590 -- general array iterator
591 --
592 -- * corresponds to `loopA' from ``Functional Array Fusion'', Chakravarty &
593 --   Keller, ICFP 2001
594 --
595 loop :: (e -> acc -> (Maybe e', acc))    -- mapping & folding, once per element
596      -> acc                              -- initial acc value
597      -> [:e:]                            -- input array
598      -> ([:e':], acc)
599 {-# INLINE loop #-}
600 loop mf acc arr = loopFromTo 0 (lengthP arr - 1) mf acc arr
601
602 -- general array iterator with bounds
603 --
604 loopFromTo :: Int                        -- from index
605            -> Int                        -- to index
606            -> (e -> acc -> (Maybe e', acc))
607            -> acc
608            -> [:e:]
609            -> ([:e':], acc)
610 {-# INLINE loopFromTo #-}
611 loopFromTo from to mf start arr = runST (do
612   marr      <- newArray (to - from + 1) noElem
613   (n', acc) <- trans from to marr arr mf start
614   arr       <- mkPArr n' marr
615   return (arr, acc))
616   where
617     noElem = error "GHC.PArr.loopFromTo: I do not exist!"
618              -- unlike standard Haskell arrays, this value represents an
619              -- internal error
620
621 -- actual loop body of `loop'
622 --
623 -- * for this to be really efficient, it has to be translated with the
624 --   constructor specialisation phase "SpecConstr" switched on; as of GHC 5.03
625 --   this requires an optimisation level of at least -O2
626 --
627 trans :: Int                            -- index of first elem to process
628       -> Int                            -- index of last elem to process
629       -> MPArr s e'                     -- destination array
630       -> [:e:]                          -- source array
631       -> (e -> acc -> (Maybe e', acc))  -- mutator
632       -> acc                            -- initial accumulator
633       -> ST s (Int, acc)                -- final destination length/final acc
634 {-# INLINE trans #-}
635 trans from to marr arr mf start = trans' from 0 start
636   where
637     trans' arrOff marrOff acc 
638       | arrOff > to = return (marrOff, acc)
639       | otherwise   = do
640                         let (oe', acc') = mf (arr `indexPArr` arrOff) acc
641                         marrOff' <- case oe' of
642                                       Nothing -> return marrOff 
643                                       Just e' -> do
644                                         writeMPArr marr marrOff e'
645                                         return $ marrOff + 1
646                         trans' (arrOff + 1) marrOff' acc'
647
648 -- Permute the given elements into the mutable array.
649 --
650 permute :: MPArr s e -> [:Int:] -> [:e:] -> ST s ()
651 permute marr is es = perm 0
652   where
653     perm i
654       | i == n = return ()
655       | otherwise  = writeMPArr marr (is!:i) (es!:i) >> perm (i + 1)
656       where
657         n = lengthP is
658
659
660 -- common patterns for using `loop'
661 --
662
663 -- initial value for the accumulator when the accumulator is not needed
664 --
665 noAL :: ()
666 noAL  = ()
667
668 -- `loop' mutator maps a function over array elements
669 --
670 mapEFL   :: (e -> e') -> (e -> () -> (Maybe e', ()))
671 {-# INLINE mapEFL #-}
672 mapEFL f  = \e a -> (Just $ f e, ())
673
674 -- `loop' mutator that filter elements according to a predicate
675 --
676 filterEFL   :: (e -> Bool) -> (e -> () -> (Maybe e, ()))
677 {-# INLINE filterEFL #-}
678 filterEFL p  = \e a -> if p e then (Just e, ()) else (Nothing, ())
679
680 -- `loop' mutator for array folding
681 --
682 foldEFL   :: (e -> acc -> acc) -> (e -> acc -> (Maybe (), acc))
683 {-# INLINE foldEFL #-}
684 foldEFL f  = \e a -> (Nothing, f e a)
685
686 -- `loop' mutator for array scanning
687 --
688 scanEFL   :: (e -> acc -> acc) -> (e -> acc -> (Maybe acc, acc))
689 {-# INLINE scanEFL #-}
690 scanEFL f  = \e a -> (Just a, f e a)
691
692 -- elementary array operations
693 --
694
695 -- unlifted array indexing 
696 --
697 indexPArr                       :: [:e:] -> Int -> e
698 {-# INLINE indexPArr #-}
699 indexPArr (PArr n# arr#) (I# i#) 
700   | i# >=# 0# && i# <# n# =
701     case indexArray# arr# i# of (# e #) -> e
702   | otherwise = error $ "indexPArr: out of bounds parallel array index; " ++
703                         "idx = " ++ show (I# i#) ++ ", arr len = "
704                         ++ show (I# n#)
705
706 -- encapsulate writing into a mutable array into the `ST' monad
707 --
708 writeMPArr                           :: MPArr s e -> Int -> e -> ST s ()
709 {-# INLINE writeMPArr #-}
710 writeMPArr (MPArr n# marr#) (I# i#) e 
711   | i# >=# 0# && i# <# n# =
712     ST $ \s# ->
713     case writeArray# marr# i# e s# of s'# -> (# s'#, () #)
714   | otherwise = error $ "writeMPArr: out of bounds parallel array index; " ++
715                         "idx = " ++ show (I# i#) ++ ", arr len = "
716                         ++ show (I# n#)
717
718 #endif /* __HADDOCK__ */
719