如何将逗号分隔值的字符串解析为haskell中的字符串列表? [英] how to parse a string of comma-separated values into a list of strings in haskell?
问题描述
因此,如果我在其中的单词列表中有一个字符串(this,is,a,故事,所有关于,如何)" ["this","is","a","story",全部",关于",如何"]作为ReadP String的实例?我尝试了很多不同的方法,其中之一是:
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? 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
为
parseLet = (many parseStr) +++ parseLast
但是那也不起作用.有小费吗?
but that didn't work either. Any tips?
更多定义
isAlphaOrDigit :: Char -> Bool
isAlphaOrDigit a = (isDigit a) || (isAlpha a)
comma = satisfy (','==)
skipComma = const () <$> some comma
推荐答案
解析器 a +++ b
将整个输入字符串发送到 a
到 b
,生成解析器生成的所有结果.相反,您需要一个解析器,将字符串的第一部分发送到 a
,将第二部分发送到 b
,然后让您合并结果.尝试以下方法:
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. 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. Try this instead:
parseLet = liftA2 (\ss s -> ss ++ [s]) (many parseStr) parseLast
许多解析器库也为这个确切的用例提供了 manySepBy
组合器(也许名称略有不同).您可以考虑在 ReadP
库中查找此类内容.
Many parser libraries also offer a manySepBy
combinator (perhaps with a slightly different name) for this exact use case; you might consider looking through the ReadP
library for such a thing.
这篇关于如何将逗号分隔值的字符串解析为haskell中的字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!