我正在使用读取文件sourceFile
,但我还需要在处理操作中引入随机性。我认为最好的方法是拥有一个这样的制片人
Producer m (StdGen, ByteString)
其中 StdGen 用于生成随机数。
我打算让生产者执行 sourceFile 的任务,并在每次向下游发送数据时生成一个新的种子来生成。
我的问题是,似乎没有像这样的源组合器zipSink
用于水槽。通读一遍导管概述 https://www.fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/conduit-overview,这似乎建议您可以嵌入一个Source
里面一个Conduit
,但我看不出示例中是如何完成的。
谁能提供一个将两个或多个 IO 源融合为一个的示例Producer
/Source
?
EDIT :
一个例子:
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
import System.Random (StdGen(..), split, newStdGen, randomR)
import ClassyPrelude.Conduit as Prelude
import Control.Monad.Trans.Resource (runResourceT, ResourceT(..))
import qualified Data.ByteString as BS
-- generate a infinite source of random number seeds
sourceStdGen :: MonadIO m => Source m StdGen
sourceStdGen = do
g <- liftIO newStdGen
loop g
where loop gin = do
let g' = fst (split gin)
yield gin
loop g'
-- combine the sources into one
sourceInput :: (MonadResource m, MonadIO m) => FilePath -> Source m (StdGen, ByteString)
sourceInput fp = getZipSource $ (,)
<$> ZipSource sourceStdGen
<*> ZipSource (sourceFile fp)
-- a simple conduit, which generates a random number from provide StdGen
-- and append the byte value to the provided ByteString
simpleConduit :: Conduit (StdGen, ByteString) (ResourceT IO) ByteString
simpleConduit = mapC process
process :: (StdGen, ByteString) -> ByteString
process (g, bs) =
let rnd = fst $ randomR (40,50) g
in bs ++ pack [rnd]
main :: IO ()
main = do
runResourceT $ sourceInput "test.txt" $$ simpleConduit =$ sinkFile "output.txt"
因此,此示例获取输入文件中的内容并将其写入输出文件,并将 40 到 50 之间的随机 ASCII 值附加到文件末尾。 (别问我为什么)