【发布时间】:2015-04-16 14:42:41
【问题描述】:
作为尝试编写 JSON 解析器的一部分,我正在解析 JSON 字符串值。
鉴于 Brent Yorgey 教授的 Haskell course 的以下定义:
-- A parser for a value of type a is a function which takes a String
-- represnting the input to be parsed, and succeeds or fails; if it
-- succeeds, it returns the parsed value along with the remainder of
-- the input.
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
我遇到了麻烦,因为据我了解,我的第二个解析器 zeroOrMore notEndOfString 只是消耗每个 token 直到到达字符串的末尾。
data JValue = S String | ...
parseStringJValue :: Parser JValue
parseStringJValue = S <$> ((char '"') *> (zeroOrMore notEndOfString) <* (char '"'))
notEndOfString :: Parser Char
notEndOfString = Parser f
where
f [] = Nothing
f (x:xs) = Just (x, xs)
使用这种应用方法,请给我一个提示,以修改我上面的parseStringJValue 以实际工作。
注意 - 我对如何使用 Monads 解决它有一个模糊的想法,但我不确定是否需要它们。
【问题讨论】:
-
提示:
notEndOfString中的字符串是您解析的结果,而不是要解析的输入。 -
你可能想要
zeroOrMore notEndOfStringOrQuote。例如,在秒差距中,我可能只会写many (noneOf "\"")。