gpt4 book ai didi

haskell - Haskell 中递归元组函数的困难

转载 作者:行者123 更新时间:2023-12-02 13:37:43 25 4
gpt4 key购买 nike

我有一个小程序,可以读取文件并将数据处理为自定义数据类型。正在读取的文件包含如下所示的数据行:

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 函数上。目前,此函数仅捕获文件的最后一行并将其打印到屏幕上。我对如何使用元组实现递归而不是在此函数中使用带有列表的追加感到困惑。谁能告诉我如何修复我的功能和/或更好地实现该功能?该程序的打印输出应为:

[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"}]

感谢您的宝贵时间。

最佳答案

你可能打算这样做

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]]仅匹配仅包含一个元素的列表,即仅包含四个元素的列表。

关于haskell - Haskell 中递归元组函数的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9897723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com