简体   繁体   English

Haskell如何创建Word8?

[英]Haskell How to Create a Word8?

I want to write a simple function which splits a ByteString into [ByteString] using '\\n' as the delimiter. 我想编写一个简单的函数,它使用'\\n'作为分隔符将ByteString拆分为[ByteString] My attempt: 我的尝试:

import Data.ByteString

listize :: ByteString -> [ByteString]
listize xs = Data.ByteString.splitWith (=='\n') xs

This throws an error because '\\n' is a Char rather than a Word8 , which is what Data.ByteString.splitWith is expecting. 这会引发错误,因为'\\n'Char而不是Word8 ,这正是Data.ByteString.splitWith所期望的。

How do I turn this simple character into a Word8 that ByteString will play with? 如何将这个简单的字符转换为ByteString将使用的Word8

You could just use the numeric literal 10 , but if you want to convert the character literal you can use fromIntegral (ord '\\n') (the fromIntegral is required to convert the Int that ord returns into a Word8 ). 你可以只使用数字文字10 ,但如果你想将字符转换的文字,你可以使用fromIntegral (ord '\\n')fromIntegral需要将转换Intord返回到Word8 )。 You'll have to import Data.Char for ord . 你必须为ord导入Data.Char

You could also import Data.ByteString.Char8 , which offers functions for using Char instead of Word8 on the same ByteString data type. 您还可以导入Data.ByteString.Char8 ,它提供在同一ByteString数据类型上使用Char而不是Word8函数。 (Indeed, it has a lines function that does exactly what you want.) However, this is generally not recommended, as ByteString s don't store Unicode codepoints (which is what Char represents) but instead raw octets (ie Word8 s). (实际上,它有一个完全符合你想要的lines函数。)但是,这通常推荐,因为ByteString 存储Unicode代码点(这是Char代表的),而是存储原始八位字节(即Word8 )。

If you're processing textual data, you should consider using Text instead of ByteString . 如果您正在处理文本数据,则应考虑使用Text而不是ByteString

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM