Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a haskell function to work with byte strings

Ive got this code which takes an integer 'n', and a list, then splits the list into 'n' lists.

chunk n xs = chunk' i xs
  where
    chunk' _ [] = []
    chunk' n xs = a : chunk' n b where (a,b) = splitAt n xs
    i = ceiling (fromIntegral (length xs) / fromIntegral n)

And this is an example of how it works:

*Main> chunk 5 [1..10]
[[1,2],[3,4],[5,6],[7,8],[9,10]]

Ive been trying to get this to work with the Data.ByteString library but cant figure it out.

This is the code ive been trying to use.

import qualified Data.ByteString as B
B.readFile "meow.txt" >>= (\x -> return $ chunk 4 x)

And this is the error that it gives me:

<interactive>:402:51:
    Couldn't match expected type `[a10]'
                with actual type `B.ByteString'
    In the second argument of `chunk', namely `x'
    In the second argument of `($)', namely `chunk 4 x'
    In the expression: return $ chunk 4 x

It appears to be a type mismatch problem, im assuming because of the fromIntegral. Is there any way to get the chunk function to accept byte strings?

My goal with this function is to strictly accept a binary file of arbitrary length, then split it into 4 pieces of approximately equal length without losing any of the data in the process.

like image 529
Ron Watkins Avatar asked Jul 29 '26 02:07

Ron Watkins


1 Answers

Byte strings are not lists. You will have to write a separate function.

But it is a simple translation. Assuming you have import qualified Data.ByteString as B, then

chunkBytes :: Int -> B.ByteString -> [B.ByteString]
chunkBytes n xs = chunk' i xs
  where
    chunk' n xs
        | B.null xs = []
        | otherwise = a : chunk' n b where (a,b) = B.splitAt n xs
    i = ceiling (fromIntegral (B.length xs) / fromIntegral n)
like image 183
dave4420 Avatar answered Jul 30 '26 20:07

dave4420



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!