1

我一直在使用这个页面 http://book.realworldhaskell.org/read/using-parsec.html 我正在尝试让一个 CSV 文件解析器工作,但我注意到

parse csvFile "(stdin)" str

总是返回一个

Right [["s","o"],["h","i"]]

有没有办法进行解析,它只返回我稍后可以在我的代码中使用的数组数组?

例如代码:

main = mainLoop []

mainLoop :: [[String]] -> IO ()
mainLoop db = do
     answer <- getLine
     case words answer of
        ("load":x) -> do
                str <- readFile (head x)
                mainLoop $ parseCSV str
        ("quit":_) -> return ()
        ("help":_) -> do 
                        putStrLn "This is your help"
                        mainLoop db
        otherwise  -> putStrLn "Not sure what you want me to do! :(" >> mainLoop db

csvFile = endBy line eol
line = sepBy cell (char ',')
cell = many (noneOf ",\n")
eol = char '\n'

parseCSV :: String -> Either ParseError [[String]]
parseCSV input = parse csvFile "(unknown)" input

谢谢

4

1 回答 1

2

简单的Right ...意思是操作可能有错误。case您可以使用以下语句处理此问题:

case parse csvFile "(stdin)" str of
  Left  err -> handle err
  Right res -> doStuff res

整个Either设计模式让您可以很好地处理代码中的任意错误。您可以随心所欲地处理错误,并且不必担心 Haskeller 讨厌的运行时异常。

正如 Thomas 在评论中有用地指出的那样,您也可以使用该either函数来执行与 case 语句相同的操作。

于 2011-12-06T23:15:37.457 回答