blob: ba711b64d69fb637c261eb58a964a4e0da3bd5d8 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
{-# LANGUAGE BangPatterns, MagicHash, UnboxedTuples, DefaultSignatures, TypeOperators, FlexibleContexts #-}
module Parallel
(NFData, parMap, rdeepseq) where
import Control.Monad
import GHC.Exts
import Control.DeepSeq
infixl 0 `using`
type Strategy a = a -> Eval a
newtype Eval a = Eval (State# RealWorld -> (# State# RealWorld, a #))
instance Functor Eval where
fmap = liftM
instance Applicative Eval where
pure x = Eval $ \s -> (# s, x #)
(<*>) = ap
instance Monad Eval where
return = pure
Eval x >>= k = Eval $ \s -> case x s of
(# s', a #) -> case k a of
Eval f -> f s'
rpar :: Strategy a
rpar x = Eval $ \s -> spark# x s
rparWith :: Strategy a -> Strategy a
rparWith s a = do l <- rpar r; return (case l of Lift x -> x)
where r = case s a of
Eval f -> case f realWorld# of
(# _, a' #) -> Lift a'
data Lift a = Lift a
using :: a -> Strategy a -> a
x `using` strat = runEval (strat x)
rdeepseq :: NFData a => Strategy a
rdeepseq x = do rseq (rnf x); return x
parList :: Strategy a -> Strategy [a]
parList strat = traverse (rparWith strat)
parMap :: Strategy b -> (a -> b) -> [a] -> [b]
parMap strat f = (`using` parList strat) . map f
runEval :: Eval a -> a
runEval (Eval x) = case x realWorld# of (# _, a #) -> a
rseq :: Strategy a
rseq x = Eval $ \s -> seq# x s
|