ByteString 的 chunksOf 模拟?
chunksOf analog for ByteString?
我需要将字节串拆分为字节串列表,第一个潜水 100 个字符。对于列表,我可以使用 chunksOf
但不能使用 ByteString
。
有什么正确的方法吗?
ByteString
和 Lazy.Bytestring
都有 splitAt
functions which you can use to 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"
我需要将字节串拆分为字节串列表,第一个潜水 100 个字符。对于列表,我可以使用 chunksOf
但不能使用 ByteString
。
有什么正确的方法吗?
ByteString
和 Lazy.Bytestring
都有 splitAt
functions which you can use to 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"