2011-06-11 50 views
1

这看起来很简单,但由于某种原因,我很困惑自己。 “事情”一行给了我错误。
解析功能正确(从RWH盗取)。我只是有一个类型错误。从openFile内容解析

谢谢!

import Text.ParserCombinators.Parsec 
import System.IO 

main = do 
    csv_cont <- openFile "aCSV.txt" ReadMode 
    csv_cont1 <- hGetContents csv_cont 
    thing <- parseCSV csv_cont1 
    return() 


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 

回答

3

parseCSV是一个纯粹的功能(注意,在类型没有IO)。所以你不要用“符号”来约束它的结果。相反,只需定期let是合适的:

import Text.ParserCombinators.Parsec 
import System.IO 

main = do 
    h <- openFile "aCSV.txt" ReadMode 
    s <- hGetContents h 
    let thing = parseCSV s 
    print thing 


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

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

这里,更地道的命名和identation。

+0

完整(变形)圆。我从你的书中窃取了CSV解析代码,然后你帮我解决了我在5行以下搞砸的地方:)谢谢。 – amindfv 2011-06-11 23:30:04

+0

不用担心,祝你好运! – 2011-06-11 23:34:10