2015-09-28 4 views
3

Je dois diviser la chaîne d'octets en une liste de chaînes d'octets plongeant la première par 100 caractères. Pour les listes, je peux utiliser chunksOf mais pas pour ByteString.chunksDe l'analogique pour ByteString?

Existe-t-il un moyen approprié de le faire?

Répondre

4

Les deux ByteString et Lazy.Bytestring ont splitAtfunctions 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" 
+0

C'est exactement ce que je cherchais. Merci pour la description complète. –