简体   繁体   English

如何将一串逗号分隔值解析为haskell中的字符串列表?

[英]how to parse a string of comma-separated values into a list of strings in haskell?

so if I have a string "(this, is, a, story, all, about, how)" into a list of the words inside it ["this", "is", "a", "story", "all", "about", "how"] as an instance of ReadP String? 所以,如果我有一个字符串“(这,是,a,故事,所有,关于,如何)”进入其中的单词列表[“this”,“is”,“a”,“story”,“all “,”关于“,”如何“]作为ReadP String的实例? I've tried a bunch of different ways, one of which being this: 我尝试了很多不同的方法,其中之一就是:

parseStr :: ReadP String
parseStr = do
  skipSpaces
  n <- munch1 isAlphaOrDigit
  skipComma
  return $ n

which parses all values but the last. 它解析所有值,但最后一个。 I thought if I combined it with this parse: 我想如果我将它与这个解析结合起来:

parseLast :: ReadP String
parseLast = do
  skipSpaces
  n <- munch1 isAlphaOrDigit
  return $ n

as

parseLet = (many parseStr) +++ parseLast

but that didn't work either. 但那也不起作用。 Any tips? 有小费吗?

edit: more definitions 编辑:更多定义

isAlphaOrDigit :: Char -> Bool 
isAlphaOrDigit a = (isDigit a) || (isAlpha a) 
comma = satisfy (','==)
skipComma = const () <$> some comma

The parser a +++ b sends the entire input string to a and the entire input string to b , producing all the results that either parser produced. 解析器a +++ b将整个输入字符串发送到a ,将整个输入字符串发送到b ,生成解析器生成的所有结果。 You instead want a parser that sends the first part of the string to a and the second part to b , then lets you combine the results. 您需要一个将字符串的第一部分发送到a而第二部分发送到b的解析器,然后让您组合结果。 Try this instead: 试试这个:

parseLet = liftA2 (\ss s -> ss ++ [s]) (many parseStr) parseLast

Many parser libraries also offer a manySepBy combinator (perhaps with a slightly different name) for this exact use case; 对于这个确切的用例,许多解析器库还提供了一个manySepBy组合器(可能名称略有不同); you might consider looking through the ReadP library for such a thing. 您可以考虑通过ReadP库查看这样的事情。

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

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