Les deux ByteString
et Lazy.Bytestring
ont splitAt
functions que vous pouvez utiliser pour unfoldr
une liste.
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))
bâtiment un exemple pour les chaînes d'octets est plus facile avec OverloadedStrings
{-# LANGUAGE OverloadedStrings #-}
main = do
print $ chunksOf 3 ""
print $ chunksOf 3 "Hello World!"
print $ chunksOf' 3 ""
print $ chunksOf' 3 "Hello, World"
C'est exactement ce que je cherchais. Merci pour la description complète. –