学习使用 Parsec 库,这是家庭作业的一部分。
编辑:欢迎提出使用其他库的建议,重点是解析。
我想要的是从任何句子中提取所有带有大写字母和四个罗盘方向的单词。例如:“比利时完全位于荷兰南部。” 应该找到并返回“比利时南荷兰”。
我想不通的是如何忽略(吃掉)任何不是指南针方向的输入。我正在寻找类似的东西
'many (not compassDirection >> space)'
但是 g(h)oogle 并没有帮助我。
以下代码显然停留在“许多”功能上。
readExpr :: String -> String
readExpr input = case parse (parseLine) "" input of
Left err -> "No match: " ++ show err
Right val -> "Found: " ++ showVal val
parseLine :: Parser GraphValue
parseLine = do
x <- parseCountry
space
many ( some (noneOf " ") >> space )
y <- parseCompass
space
many ( some (noneOf " ") >> space )
z <- parseCountry
return $ Direction [x,y,z]
compassDirection :: Parser String
compassDirection = string "north" <|>
string "south" <|>
string "east" <|>
string "west"
parseCountry :: Parser GraphValue
parseCountry = do
c <- upper
x <- many (lower)
return $ Country (c:x)
parseCompass :: Parser GraphValue
parseCompass = do
x <- compassDirection
return $ Compass x