chunksOf模拟ByteString?

时间:2015-09-28 15:24:09

标签: haskell bytestring

我需要将bytestring分成多个字节串列表,首先跳过100个字符。对于列表,我可以使用chunksOf但不能使用ByteString

有没有正确的方法来做到这一点?

1 个答案:

答案 0 :(得分:4)

ByteStringLazy.Bytestring都有splitAt functions,您可以使用unfoldr列表。

import Data.List (unfoldr)
import Data.Int (Int64)

import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as Lazy

justWhen :: (a -> Bool) -> (a -> b) -> (a -> Maybe b)
justWhen f g a = if f a then Just (g a) else Nothing

nothingWhen :: (a -> Bool) -> (a -> b) -> (a -> Maybe b)
nothingWhen f = justWhen (not . f)

chunksOf :: Int -> BS.ByteString -> [BS.ByteString]
chunksOf x = unfoldr (nothingWhen BS.null (BS.splitAt x))

chunksOf' :: Int64 -> Lazy.ByteString -> [Lazy.ByteString]
chunksOf' x = unfoldr (nothingWhen Lazy.null (Lazy.splitAt x))

使用OverloadedStrings

可以更轻松地构建示例的字节串
{-# LANGUAGE OverloadedStrings #-}

main = do
    print $ chunksOf 3 ""
    print $ chunksOf 3 "Hello World!"
    print $ chunksOf' 3 ""
    print $ chunksOf' 3 "Hello, World"