从 Haskell 中字符的字符串表示创建 ByteString

Creating ByteString from String representation of chars in Haskell

我正在尝试从已转换为字节字符的字符串创建 Char8 字节字符串。

例如,对于字符串“65”,我想要 ByteString,其解包方法将给我“A”。因为65等于chr 65。如果此方法能够处理十六进制表示中的数字,那就更好了。所以我想要这样的东西:

toByteString :: String -> ByteString
toByteString s = **** s

--Numbers bettwen 0 and 255 or 00 and ff
someBS = toByteString " 72 97 115 107 104 101 108 108" -- evaluates to ByteString

str :: String
str bs = unpack someBS -- evaluates to "Haskhell" 

我已经尝试在 ByteString.Char8Char 的文档中找到我想要的东西,但这些库中似乎没有适合我的目的的内置方法。也许我错过了什么。

我认为一定有一种方法可以从 chars 创建 ByteString,但不知怎么的,它不够明显,无法找到它

如果可以,请不要从 String 开始。例如,原生 Haskell 语法已经支持十进制和十六进制数字:

Data.ByteString> pack [72, 97, 115, 107, 104, 101, 108, 108]
"Haskhell"
Data.ByteString> pack [0x48, 0x61, 0x73, 0x6b, 0x68, 0x65, 0x6c, 0x6c]
"Haskhell"

如果您必须从 String 开始,任何解析器组合器库都可以很好地让您从 " 72 97 115"[72, 97, 115] —— 甚至只是 map read . words

> import qualified Data.ByteString as BS
BS> BS.pack . map read . words $ " 72 97 115 107 0x68 0x65 0x6c 0x6c"
"Haskhell"