【问题标题】:Parse a string of length at least one character解析长度至少为一个字符的字符串
【发布时间】:2017-04-24 17:17:25
【问题描述】:

我正在尝试用 Haskell 编写解析器。在这我需要一个解析长度至少为 1 的字符串的函数。我有下面声明的类型:

type Pname = String

但是我的功能不起作用。我的代码如下,sc 是我的空白和 cmets 的空间使用者(我一直在关注https://mrkkrp.github.io/megaparsec/tutorials/parsing-simple-imperative-language.html 的教程以获取有关此解析器的帮助):

pname :: Parser Pname
pname = (some ['a' .. 'z']) <* sc

但它给了我错误:

    Couldn't match type ‘[]’
                   with ‘ParsecT Dec String Data.Functor.Identity.Identity’
    Expected type: ParsecT
                     Dec String Data.Functor.Identity.Identity Char
      Actual type: [Char]
    In the first argument of ‘some’, namely ‘['a' .. 'z']’
    In the first argument of ‘(<*)’, namely ‘(some ['a' .. 'z'])’
    In the expression: (some ['a' .. 'z']) <* sc

关于为什么这不起作用的任何想法?

【问题讨论】:

    标签: haskell


    【解决方案1】:

    您可能打算使用oneOf(或解析器库中的类似函数)

    pname = some (oneOf ['a' .. 'z']) <* sc
    

    将字符列表转换为接受其中一个字符的解析器。

    【讨论】:

    • 我需要它来接受一个或多个字符,因此我认为 oneOf 不合适?
    • @datguywelbz oneOf ['a' .. 'z'] 只接受一个字符;但some (oneOf ['a' .. 'z']) 接受一个或多个(参见documentation for some)。
    猜你喜欢
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    相关资源
    最近更新 更多