我有一个小程序,它读入文件并将数据处理成自定义数据类型。正在读取的文件包含如下所示的数据行:
cat 10 20 dog
hamster 12 2 wombat
monkey 1 9 zebra
lion 30 60 rhino
...
我处理文件的程序如下所示:
main :: IO ()
main = do
contents <- readFile "myfile.xyz"
let process = clean contents
let f = processFile process
print f
clean :: String -> [[String]]
clean x = Prelude.map words $ lines x
processFile :: [[String]] -> [(XyzData)]
processFile [[a,b,c,d]] = [(XyzData a (read b :: Int) (read c :: Int) d)]
processFile (x:xs) = processFile xs
data XyzData = XyzData { animal1 :: String,
number1 :: Int,
number2 :: Int,
animal2 :: String
} deriving (Show)
我的问题在于processFile
功能。目前,此功能仅捕获文件的最后一行并将其打印到屏幕上。我对如何使用元组实现递归而不是在此函数中使用带有列表的append感到困惑。谁能告诉我如何修复我的功能和/或更好地实现这个功能?该程序的打印输出应为:
[XyzData {animal1 = "cat", number1 = 10, number2 = 20, animal2 = "dog"},
[XyzData {animal1 = "hampster", number1 = 12, number2 = 2, animal2 = "wombat"},
[XyzData {animal1 = "monkey", number1 = 1, number2 = 9, animal2 = "zebra"},
[XyzData {animal1 = "lion", number1 = 30, number2 = 60, animal2 = "rhino"}]
感谢您的时间。
答案 0 :(得分:8)
你可能打算
processFile :: [[String]] -> [(XyzData)]
processFile ([a,b,c,d]:xs) = (XyzData a (read b :: Int) (read c :: Int) d) : processFile xs
processFile (x:xs) = processFile xs
processFile [] = []
您的第一个模式[[a,b,c,d]]
仅匹配包含一个元素的列表,这是一个包含四个元素的列表。