Skip to content

Embed ST actions in Eval #41

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Control/Parallel/Strategies.hs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{-# LANGUAGE BangPatterns, CPP, MagicHash, UnboxedTuples #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Parallel.Strategies
Expand Down Expand Up @@ -118,6 +119,7 @@ module Control.Parallel.Strategies (
, Eval -- instances: Monad, Functor, Applicative
, runEval -- :: Eval a -> a
, runEvalIO -- :: Eval a -> IO a
, stToEval -- :: (forall s. ST s a) -> Eval a
,

-- * API History
Expand Down Expand Up @@ -150,6 +152,12 @@ import Control.Applicative
import Control.Parallel
import Control.DeepSeq (NFData(rnf))

#if __GLASGOW_HASKELL__ >= 702
import Control.Monad.ST.Strict (ST, stToIO)
#else
import Control.Monad.ST.Strict (ST, runST)
#endif

#if MIN_VERSION_base(4,4,0)
import System.IO.Unsafe (unsafeDupablePerformIO)
import Control.Exception (evaluate)
Expand Down Expand Up @@ -224,6 +232,16 @@ runEval = unsafePerformIO . unEval_
runEvalIO :: Eval a -> IO a
runEvalIO = unEval_

-- | Run an 'ST' computation in the 'Eval' monad.
--
-- > stToEval m = runST (pure <$> m)
stToEval :: (forall s. ST s a) -> Eval a
-- Do not be tempted to allow non-closed ST computations (i.e., to
-- drop the forall). ST computations using the same mutable
-- references and arrays could end up running in parallel, stepping
-- on each other's toes.
stToEval m = Eval (stToIO m)

#else

data Eval a = Done a
Expand All @@ -237,6 +255,15 @@ runEval (Done x) = x
runEvalIO :: Eval a -> IO a
runEvalIO (Done x) = return x

-- | Run an 'ST' computation in the 'Eval' monad.
--
-- > stToEval m = runST (pure <$> m)
stToEval :: (forall s. ST s a) -> Eval a
-- It must be runST (Eval <$> m) and not Eval (runST m). The
-- latter will delay the ST computation until its result is
-- forced to WHNF. We want to run it immediately.
stToEval m = runST (pure <$> m)

instance Functor Eval where
fmap = liftM

Expand Down