## Par/Pseq-Beispiel

```{-# language PatternSignatures #-}

import Data.List (partition)
import Control.Parallel
import Control.Parallel.Strategies

import System.Environment
import System.Random
import System.IO
import Data.Time.Clock

main = do
[ n ] <- getArgs
gen <- newStdGen
let xs :: [ Int ] = take ( read n )
\$ randomRs ( 0, 1000 ) gen
print \$ sum xs
start <- getCurrentTime
print \$ sum \$ sort4 2 xs
end <- getCurrentTime
print \$ diffUTCTime end start

-- standard (naives Quicksort, Pivot steht links)
sort1 [] = []
sort1 (x:xs) =
let (lo,hi) = Data.List.partition (<x) xs
slo = sort1 lo ; shi = sort1 hi
in  slo ++ x : shi

-- parallele Auswertung
sort2 [] = []
sort2 (x:xs) =
let (lo,hi) = Data.List.partition (<x) xs
slo = sort2 lo ; shi = sort2 hi
in  slo `par` shi `pseq`
( slo ++ x : shi )

-- ... nur für Rekursionen am Anfang
sort3 d xs | null xs || d <= 0 = sort1 xs
sort3 d (x:xs) =
let (lo,hi) = partition (<x) xs
slo = sort3 (d-1) lo
shi = sort3 (d-1) hi
in  slo `par` shi `pseq`
( slo ++ x : shi )

-- ... mit kompletter Forcierung der Resultate
sort4 d xs | null xs || d <= 0 = sort1 xs
sort4 d (x:xs) =
let (lo,hi) = partition (<x) xs
slo = sort4 (d-1) lo
shi = sort4 (d-1) hi
in  force slo `par` force shi `pseq`
( slo ++ x : shi )

force xs = xs `using` rdeepseq
```

Johannes Waldmann 2010-01-25