Haskell如何创建一个Word8? [英] Haskell How to Create a Word8?

查看:100
本文介绍了Haskell如何创建一个Word8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个简单的函数,使用 ByteString 分成 [ByteString] >'\\\
'
作为分隔符。我的尝试:

  import Data.ByteString 

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

由于'\ n' Char 而不是<$ c $,所以会引发错误c> Word8 ,这就是 Data.ByteString.splitWith 正在期待中。



如何将这个简单字符转换为 Word8 ByteString 会玩什么?

解决方案

您可以使用数字文字 10 ,但是如果你想转换字符,你可以使用 fromIntegral(ord'\\\
')
fromInteral 才能将 ord 返回的 Int 转换为 Word8 )。您必须为 ord 导入 Data.Char



您也可以导入 数据.ByteString.Char8 ,它提供了使用 Char 而不是 Word8 在同一个 ByteString 数据类型上。 (的确,它有一个 <$ c $ )然而,这通常不是 推荐的,因为 ByteString s 不会存储Unicode代码点(这是 Char 代表的内容),而是存储原始八位字节(即 Word8 $ b

如果你正在处理文本数据,你应该考虑使用 Text 而不是 ByteString


I want to write a simple function which splits a ByteString into [ByteString] using '\n' as the delimiter. 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.

How do I turn this simple character into a Word8 that ByteString will play with?

解决方案

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). You'll have to import Data.Char for ord.

You could also import Data.ByteString.Char8, which offers functions for using Char instead of Word8 on the same ByteString data type. (Indeed, it has a lines function that does exactly what you want.) However, this is generally not recommended, as ByteStrings don't store Unicode codepoints (which is what Char represents) but instead raw octets (i.e. Word8s).

If you're processing textual data, you should consider using Text instead of ByteString.

这篇关于Haskell如何创建一个Word8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆