我需要将bytestring分成多个字节串列表,首先跳过100个字符。对于列表,我可以使用chunksOf
但不能使用ByteString
。
有没有正确的方法来做到这一点?
答案 0 :(得分:4)
ByteString
和Lazy.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"