簡體   English   中英

Haskell 枚舉器:類似於 iteratees `enumWith` 運算符?

[英]Haskell enumerator: analog to iteratees `enumWith` operator?

今天早些時候,我為 iteratees 編寫了一個小型測試應用程序,它組成了一個 iteratee,用於編寫進度,一個 iteratee 用於實際復制數據。 我最終得到了這樣的價值觀:

-- NOTE: this snippet is with iteratees-0.8.5.0
-- side effect: display progress on stdout
displayProgress :: Iteratee ByteString IO ()

-- side effect: copy the bytestrings of Iteratee to Handle
fileSink :: Handle -> Iteratee ByteString IO ()

writeAndDisplayProgress :: Handle -> Iteratee ByteString IO ()
writeAndDisplayProgress handle = sequence_ [fileSink handle, displayProgress]

在查看枚舉器庫時,我看不到sequence_enumWith的類似物。 我想做的就是組合兩個迭代器,以便它們作為一個迭代器。 我可以丟棄結果(無論如何它都會是() )或保留它,我不在乎。 (&&&) 來自 Control.Arrow 是我想要的,僅適用於迭代而不是箭頭。

我嘗試了這兩個選項:

-- NOTE: this snippet is with enumerator-0.4.10
run_ $ enumFile source $$ sequence_ [iterHandle handle, displayProgress]
run_ $ enumFile source $$ sequence_ [displayProgress, iterHandle handle]

第一個復制文件,但不顯示進度; 第二個顯示進度,但不復制文件,所以顯然內置 sequence_ 對枚舉器的迭代器的影響是運行第一個迭代器直到它終止然后運行另一個,這不是我想要的。 我想並行而不是串行運行迭代器。 我覺得我遺漏了一些明顯的東西,但是在閱讀枚舉器庫的wc示例時,我看到了這個奇怪的評論:

-- Exactly matching wc's output is too annoying, so this example
-- will just print one line per file, and support counting at most
-- one statistic per run

我想知道這句話是否表明在枚舉框架內組合或組合迭代器是不可能的。 普遍接受的正確方法是什么?

編輯

似乎沒有內置的方法可以做到這一點。 Haskell 郵件列表上有關於添加諸如enumSequencemanyToOne之類的組合子的討論,但到目前為止,在枚舉器 package 中似乎沒有任何實際提供此功能的東西。

在我看來,與其試圖讓兩個Iteratees並行消耗序列,不如通過一個簡單地計算通過它的字節數的身份Enumeratee來提供 stream 會更好。

這是一個簡單的示例,它復制文件並打印每個塊之后復制的字節數。

import System.Environment
import System.IO
import Data.Enumerator
import Data.Enumerator.Binary (enumFile, iterHandle)
import Data.Enumerator.List (mapAccumM)
import qualified Data.ByteString as B

printBytes :: Enumeratee B.ByteString B.ByteString IO ()
printBytes = flip mapAccumM 0 $ \total bytes -> do
    let total' = total + B.length bytes
    print total'
    return (total', bytes)

copyFile s t = withBinaryFile t WriteMode $ \h -> do
    run_ $ (enumFile s $= printBytes) $$ iterHandle h

main = do
    [source, target] <- getArgs
    copyFile source target

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM