我想为足球比分写一个小解析器。
例如,输入"0:2"
应解析为Just (Score 0 2)
。如果有类似的"3:3"
事情应该给我"Nothing"
。其他所有的东西也应该给我"Nothing"
。
data Score = Score Int Int
deriving (Eq,Show,Ord)
runParsec :: Parser a -> String -> Maybe a
runParsec parser input = case runP parser () "" input of
Left _ -> Nothing
Right a -> Just a
我给runParsec作为参数的解析器看起来像这样:
parseScore :: Parser Score
parseScore str1 = case str1 of
"x:y" && (x /= y) -> Right Score x y
Otherwise -> Left x
我知道,parseScore的此代码无法正常工作。因为我无法使用“ x:y”之类的字符串来进行模式匹配。但是我该如何解决这个问题呢?
runParsec parseScore "0:2"
应该给我 Just (Score 0 2)
我很感谢提示。
谢谢!
只需Parser
为您的类型写一个适当的代码,然后过滤掉不需要的内容即可:
import Control.Applicative ((<$>))
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Char
data Score = Score Int Int deriving (Show)
parseScore :: Parser Score
parseScore = do
a <- integer
char ':'
b <- integer
return $ Score a b
integer :: Parser Int
integer = read <$> many1 digit
runParsec :: String -> Maybe Score
runParsec input = case parse parseScore "" input of
Left e -> Nothing
Right e -> case e of
Score 0 2 -> Just e
_ -> Nothing
演示ghci
:
λ> runParsec "0:2"
Just (Score 0 2)
λ> runParsec "3:3"
Nothing
λ> runParsec "3:4"
Nothing
如果我想接受所有分数1:0、0:4等,该怎么办?一切,但没有像“ jirjgir”这样的随机输入,也没有像“ 2:2”或“ 5:5”这样的均等分数
只需更改您的过滤条件:
runParsec :: String -> Maybe Score
runParsec input = case parse parseScore "" input of
Left e -> Nothing
Right e -> case e of
Score x y -> if x == y
then Nothing
else Just e
演示:
λ> runParsec "1:0"
Just (Score 1 0)
λ> runParsec "0:4"
Just (Score 0 4)
λ> runParsec "2:2"
Nothing
λ> runParsec "jiraf"
Nothing
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句