我有一个小程序,它读入文件并将数据处理成自定义数据类型.正在读取的文件包含如下所示的数据行:
cat 10 20 dog
hamster 12 2 wombat
monkey 1 9 zebra
lion 30 60 rhino
...
Run Code Online (Sandbox Code Playgroud)
我处理文件的程序如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
我的问题在于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"}]
Run Code Online (Sandbox Code Playgroud)
谢谢你的时间.
你可能打算
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 [] = []
Run Code Online (Sandbox Code Playgroud)
您的第一个模式[[a,b,c,d]]仅匹配具有一个元素的列表,该列表具有恰好四个元素.
| 归档时间: |
|
| 查看次数: |
570 次 |
| 最近记录: |