简体   繁体   English

在Haskell中从ByteString解析各种整数的通用有效方法

[英]Generic and efficient way to parse various kinds of integers from ByteStrings in Haskell

Here's what I could come up with but I don't think it's very efficient or safe: 这是我能想到的,但我认为它不是非常有效或安全的:

import qualified Data.ByteString.Char8 as B8

convert2Int = read . B8.unpack

Is there a better way to do this? 有一个更好的方法吗? I found functions in libraries that do it for the Int type, but not for other types like Int32 , Int64 , Word64 , etc. 我在库中找到针对Int类型执行此操作的函数,但未针对其他类型(例如Int32Int64Word64等)执行此操作。

The most straightforward way is probably decode from Data.Binary : 最直接的方法可能是从Data.Binary decode

import qualified Data.ByteString.Lazy as BL
import Data.Binary (decode)

convertToIntegral :: (Binary a, Integral a) => BL.ByteString -> a
convertToIntegral = decode

There is also a decodeOrFail there, which produces an Either value if the decoding fails. 还有一个decodeOrFail那里,它产生一个Either如果解码失败值。

PS: How do I know that decode will work for the types you want? PS:我怎么知道decode将适合您想要的类型? By reading the list of Binary instances . 通过阅读Binary实例列表

An alternative way I found is to use the Attoparsec module : 我发现的另一种方法是使用Attoparsec模块

import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString as B

convertToIntegral :: (Integral a) => B.ByteString -> Either String a
convertToIntegral = parseOnly decimal

Of course, this only works for strings without signs (unlike "-3" and "+5"). 当然,这仅适用于没有符号的字符串(与“ -3”和“ +5”不同)。 One may use "signed" instead of "decimal" in these cases. 在这种情况下,可以使用“有符号”而不是“十进制”。

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

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