6

我正在将 CSV 文件解析为 CSV 类型,它是一个记录列表,它是一个字段列表,它们只是字符串。插入新行然后尝试访问 csv 后,我得到 c 堆栈溢出错误。我读过这个错误可能来自使用尾递归的太大的“thunk”,但我不认为那是我做错了什么?

type CSV = [Record]
type Record = [Field]
type Field = String

run :: IO()
run =
 do
  inFile <- readFile "myFile.csv"
  let csv = parse inFile
  let csv = (insertRow "abc,def,ghi" csv)
  putStr (show csv)

insertRow :: String -> CSV -> CSV
insertRow newRow csv = csv ++ [toRecord newRow]

parse :: String -> CSV
parse file = map toRecord (parseLines file "" [])

toRecord :: String -> Record
toRecord line = parseWords line "" []

-- parseLine input partialCSV records
parseLines :: String -> String -> [String] -> [String]
parseLines [] partial records = records ++ [partial]
parseLines ('\r':xs) partial records = parseLines xs [] (records ++ [partial])
parseLines (x:xs) partial records = parseLines xs (partial ++ [x]) records

-- parseWords input partialRecord fields
parseWords :: String -> String -> [String] -> [String]
parseWords [] partial fields = fields ++ [partial]
parseWords ('"':xs) partial fields = parseQuotes xs partial fields
parseWords (',':xs) partial fields = parseWords xs [] (fields ++ [partial])
parseWords (x:xs) partial fields = parseWords xs (partial ++ [x]) fields

parseQuotes :: String -> String -> [String] -> [String]
parseQuotes ('"':xs) partial fields = parseWords xs [] (fields ++ [partial])
parseQuotes (x:xs) partial fields = parseQuotes xs (partial ++ [x]) fields
4

2 回答 2

5

让绑定是递归的,所以这一行

let csv = (insertRow "abc,def,ghi" csv)

创建一个无限循环,您正在csv以一种不会终止的方式定义自身。将其更改为

let csv' = ...

csv'并在下一行打印。

于 2012-01-04T14:30:25.127 回答
2

替身let csv = ...看起来很可疑。你能试着解开这两个变量吗?它可能不会做你想要的(在 Haskelllet中是递归的)。

于 2012-01-04T14:29:23.873 回答