我得到了这段代码,它接受一个整数“n”和一个列表,然后将该列表拆分为“n”个列表。
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)
这是其工作原理的示例:
*Main> chunk 5 [1..10]
[[1,2],[3,4],[5,6],[7,8],[9,10]]
我一直在尝试让它与 Data.ByteString 库一起使用,但无法弄清楚。
这是我一直在尝试使用的代码。
import qualified Data.ByteString as B
B.readFile "meow.txt" >>= (\x -> return $ chunk 4 x)
这是它给我的错误:
<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
这似乎是类型不匹配问题,我假设是由于 fromIntegral
造成的。有什么方法可以让 chunk 函数接受字节字符串吗?
我使用此函数的目标是严格接受任意长度的二进制文件,然后将其拆分为长度大致相等的 4 个部分,而不会丢失该过程中的任何数据。
最佳答案
字节字符串不是列表。您必须编写一个单独的函数。
但这只是一个简单的翻译。假设您已导入合格的 Data.ByteString as B
,那么
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)
关于function - 将 haskell 函数转换为使用字节字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13219563/