Here's the original answer from Michael.
If I understand your question, it is the topic of the section on 'Pipeline Parallelism' in the Parallel and Concurrent Haskell book. See the corresponding
rsa encryption module in the code respository for the book (Note the other rsa implementions in the directory.) Here is a version which includes the little Stream library it presupposes for simplicity: http://lpaste.net/132048
Instead of using regular lists, it uses a sort of "ListT done right", so the basic types are:
data IList a = Nil | Cons a (IVar (IList a))
type Stream a = IVar (IList a)
which is basically ListT IVar a
in the sense of the standard implementations, e.g. in pipes
or list-t
and many others. (IVar isn't a functor, much less a monad, so the case is a little unusual.) The module goes on to define fromList
, map
and fold
functions, just as you were imagining. The main pipelining operation does a roundtrip of encryption and decryption:
pipeline :: Integer -> Integer -> Integer -> ByteString -> ByteString
pipeline n e d b = runPar $ do
s0 <- streamFromList (chunk (size n) b)
s1 <- streamMap (B.pack . show . power e n . code) s0 -- encrypt
s2 <- streamMap (B.pack . decode . power d n . integer) s1 -- decrypt
xs <- streamFold (\x y -> (y : x)) [] s2
return (B.unlines (reverse xs))
Here in place of your xs
we use streamFromList xs
; the first use of streamMap is like your map f xs
and the next is like your map g ys
So s0
s1
& s2
are like your xs
ys
& zs
.
These ideas are implemented in the monad-par
library, but not exposed: https://github.com/simonmar/monad-par/blob/master/monad-par/monad-par.cabal#L156