3

整数「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. バイト文字列を受け入れるチャンク関数を取得する方法はありますか?

この関数での私の目標は、任意の長さのバイナリ ファイルを厳密に受け入れ、プロセスでデータを失うことなくほぼ同じ長さの 4 つの部分に分割することです。

4

4 に答える 4

4

バイト文字列はリストではありません。別の関数を作成する必要があります。

しかし、それは簡単な翻訳です。あなたが持っていると仮定するとimport qualified 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)
于 2012-11-04T15:10:10.867 に答える
3

listlikeパッケージを使用することもできます。リストやByteStringsTextなどを操作するための統一された API を作成します。したがって、次のように記述できます。

import qualified Data.ListLike as LL

chunk :: (Integral n, LL.ListLike l a) => n -> l -> [l]
chunk n xs = chunk' i xs
  where
    chunk' n xs | LL.null xs = []
                | otherwise = a : chunk' n b where (a,b) = LL.splitAt n xs
    i = ceiling (fromIntegral (LL.length xs) / fromIntegral n)
于 2012-11-04T16:23:08.223 に答える
1

ByteString はリストではないため、Prelude.splitAtData.List からエクスポートされた で走査することはできませんB.splitAt。代わりに使用する必要があります。

于 2012-11-04T15:10:47.853 に答える
0

パターン マッチングは低レベルであり、値コンストラクターを厳密に使用して一致させます。[] と (:) は、リスト型 [a] の値コンストラクターです。バイト文字列コンストラクターは異なり、通常はユーザーにとってあまり役に立ちません。

「トラバース可能な」値など、値の形状に基づいた高レベルのマッチング形式に関心が寄せられています。しかし、私が知る限り、まだ実装はありません。

于 2012-11-05T10:51:18.860 に答える