【发布时间】:2014-04-27 10:04:17
【问题描述】:
我正在使用sourceFile 从文件中读取数据,但我还需要在处理操作中引入随机性。我认为最好的方法是有一个类型的生产者
Producer m (StdGen, ByteString)
其中 StdGen 用于生成随机数。
我打算让生产者执行 sourceFile 的任务,并在每次向下游发送数据时产生一个新的种子。
我的问题是,似乎没有像 zipSink 这样的源组合器用于接收器。通读Conduit Overview,似乎建议您可以在Conduit 中嵌入Source,但我看不到示例中是如何完成的。
谁能提供一个示例,将两个或多个 IO 源融合到一个 Producer/Source 中?
编辑:
一个例子:
{-# 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 值附加到文件末尾。 (别问我为什么)
【问题讨论】:
-
如果你想要管道中的随机性,请使用 monad random。