【问题标题】:Parse multiple instances of a string using ReadP使用 ReadP 解析字符串的多个实例
【发布时间】:2017-04-09 12:59:28
【问题描述】:

问题说明:解析"ABCDFGABIJABGHA"中的字符串"AB"

约束:使用ReadP

预期解决方案:(["AB","AB","AB"],"whatever is left")

尝试:

getAll :: ReadP a -> ReadP [a]
getAll p = many loop
  where
    loop = p <|> (get >> loop)

readP_to_S (getAll $ string "AB") "ABCDFGABIJABGHA"
[([],"ABCDFGABIJABGHA"),(["AB"],"CDFGABIJABGHA"),(["AB","AB"],"IJABGHA"),(["AB"],"IJABGHA"),(["AB","AB","AB"],"GHA"),(["AB","AB"],"GHA"),(["AB","AB"],"GHA"),(["AB"],"GHA")]

我希望最后一个状态是(["AB","AB","AB"],"GHA")。是否可以使用ReadP 做同样的事情?

【问题讨论】:

    标签: parsing haskell text-parsing string-parsing


    【解决方案1】:

    问题是您正在使用&lt;|&gt; 进行对称选择。如果您希望您的解析器毫无例外地匹配所有ps,请使用提供的左偏选择:&lt;++

    getAll :: ReadP a -> ReadP [a]
    getAll p = many loop
      where
        loop = p <++ (get >> loop)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多