我了解到Char8仅支持ASCII字符,如果您正在使用其他Unicode字符,则使用起来会很危险。
{-# LANGUAGE OverloadedStrings #-}
--import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.Text.IO as TIO
import qualified Data.Text.Encoding as E
import qualified Data.Text as T
name :: T.Text
name = "{ \"name\": \"哈时刻\" }"
nameB :: BC.ByteString
nameB = E.encodeUtf8 name
main :: IO ()
main = do
BC.writeFile "test.json" nameB
putStrLn "done"
产生与以下结果相同的结果
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString as B
--import qualified Data.ByteString.Char8 as BC
import qualified Data.Text.IO as TIO
import qualified Data.Text.Encoding as E
import qualified Data.Text as T
name :: T.Text
name = "{ \"name\": \"哈时刻\" }"
nameB :: B.ByteString
nameB = E.encodeUtf8 name
main :: IO ()
main = do
B.writeFile "test.json" nameB
putStrLn "done"
那么使用
Data.ByteString.Char8
和Data.ByteString
有什么区别 最佳答案
如果比较Data.ByteString
和Data.ByteString.Char8
,您会注意到,一堆引用Word8
的函数在前者中引用了Char
。
-- Data.ByteString
map :: (Word8 -> Word8) -> ByteString -> ByteString
cons :: Word8 -> ByteString -> ByteString
snoc :: ByteString -> Word8 -> ByteString
head :: ByteString -> Word8
uncons :: ByteString -> Maybe (Word8, ByteString)
{- and so on... -}
-- Data.ByteString.Char8
map :: (Char -> Char) -> ByteString -> ByteString
cons :: Char -> ByteString -> ByteString
snoc :: ByteString -> Char -> ByteString
head :: ByteString -> Char
uncons :: ByteString -> Maybe (Char, ByteString)
{- and so on... -}
对于这些功能以及仅这些功能,
Data.ByteString.Char8
提供了不必将Word8
值不断地转换为Char
值和从中转换出来的便利。 writeFile
在两个模块中都做完全相同的事情。 这是查看
Text
,ByteString
和ByteString.Char8
中相似功能的不同行为的一种好方法:{-# LANGUAGE OverloadedStrings #-}
import Data.Text.Encoding
import qualified Data.Text as T
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
nameText :: T.Text
nameText = "哈时刻"
nameByteString :: B.ByteString
nameByteString = encodeUtf8 nameText
main :: IO ()
main = do
print $ T.head nameText -- '\21704' actual first character
print $ B.head nameByteString -- 229 first byte
print $ BC.head nameByteString -- '\299' first byte as character
putStrLn [ T.head nameText ] -- 哈 actual first character
putStrLn [ BC.head nameByteString ] -- å first byte as character
关于haskell - Data.ByteString和Data.ByteString.Char8之间的区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47446588/