替换ByteString中的换行符

时间:2017-11-13 13:19:45

标签: haskell replace pattern-matching bytestring

我喜欢使用ByteString并用逗号替换换行符\n\n\r的函数,但不能想出一个很好的方法。

import qualified Data.ByteString as BS
import Data.Char (ord) 
import Data.Word (Word8)

endlWord8 = fromIntegral $ ord '\n' :: Word8

replace :: BS.ByteString -> BS.ByteString

我考虑过使用BS.map,但由于我无法在Word8上进行模式匹配,因此无法查看。另一种选择是BS.split,然后用Word8逗号加入,但听起来缓慢且不优雅。有任何想法吗?

1 个答案:

答案 0 :(得分:2)

使用Data.ByteString.Char8摆脱您不得不做的令人讨厌的Word8Char次转化。根据{{​​3}}表现不应改变。

另外,使用B.span代替B.split,因为您还要替换\n\r组合而不仅仅\n

我自己(可能是笨拙的)尝试这样做:

module Test where

import Data.Monoid ((<>))
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Builder as Build
import qualified Data.ByteString.Lazy as LB

eatNewline :: ByteString -> (Maybe Char, ByteString)
eatNewline string
  | B.null string = (Nothing, string)
  | B.head string == '\n' && B.null (B.tail string) = (Just ',', B.empty)
  | B.head string == '\n' && B.head (B.tail string) /= '\r' = (Just ',', B.drop 1 string)
  | B.head string == '\n' && B.head (B.tail string) == '\r' = (Just ',', B.drop 2 string)
  | otherwise = (Nothing, string)

replaceNewlines :: ByteString -> ByteString
replaceNewlines = LB.toStrict . Build.toLazyByteString . go mempty
  where
    go :: Build.Builder -> ByteString -> Build.Builder
    go builder string = let (chunk, rest) = B.span (/= '\n') string
                            (c, rest1)    = eatNewline rest
                            maybeComma    = maybe mempty Build.char8 c
                        in if B.null rest1 then
                             builder <> Build.byteString chunk <> maybeComma
                           else
                             go (builder <> Build.byteString chunk <> maybeComma) rest1

希望mappend的{​​{1}}在Data.ByteString.Builder已用于其中一个操作数的次数中不是线性的,否则,这里会出现二次算法