【问题标题】:How to parse an Integer with parsec如何使用 parsec 解析整数
【发布时间】:2014-06-11 19:25:03
【问题描述】:

我期待找到一个函数

integer :: Stream s m Char => ParsecT s u m Integer

甚至可能

natural :: Stream s m Char => ParsecT s u m Integer

在标准库中,但我没有找到。

将普通自然数直接解析为Integer 的标准方法是什么?

【问题讨论】:

标签: haskell parsec


【解决方案1】:

这里是我经常做的就是使用表达式

read <$> many1 digit

可以是Stream s m Char =&gt; ParsecT s u m Integer(或简单的Parser Integer)类型。

我不喜欢使用偏函数read,但是当解析器成功时我知道read会成功,而且它有点可读性。

【讨论】:

  • 为了清楚起见,您能否包括一个类型签名?
【解决方案2】:

查看Text.Parsec.Token的来源,Parsec似乎没有专门的功能。他们确实为GenLanguageDefdecimal 字段提供了默认定义。 decimal 的定义类似于:

decimal = do
    digits <- many1 baseDigit
    let n = foldl (\x d -> base*x + toInteger (digitToInt d)) 0 digits
    seq n (return n)
  where
    base = 10
    baseDigit = digit

这里,digit 取自 Text.Parsec.ChardigitToInt 取自 Data.Char

natural 还有一个默认定义,默认情况下,它还解析八进制和十六进制数字,并跳过尾随空格。

【讨论】:

  • 另外,this answer 非常相似,由于它的应用风格,它使用了foldl' 而不是foldl 加上一个seq 在错误的地方:)跨度>
猜你喜欢
  • 1970-01-01
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
相关资源
最近更新 更多