function - 将 haskell 函数转换为使用字节字符串

标签 function haskell binary

我得到了这段代码,它接受一个整数“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/

相关文章:

c - 将二进制解析为十进制

php - 人们曾经使用过variable.php 文件吗?

python - 如何从Python中的函数返回字典和多个变量?

haskell - 如何在计算随机值的 haskell 程序中构造 monad?

haskell - 使用部分应用的函数缓存内部

mysql - 如何将 LIKE 运算符与二进制有序时间 UUID 结合使用

C++ |如何格式化和导出由二维矩阵组成的简单二进制文件

function - Haskell 中的折叠实现

c# - 通过 Interop/pinvoke 传递 C# 回调函数

haskell - 为什么map (^2) xs 和map (2^) xs 在Haskell 中都能按预期工作?