Reputation: 10689
I have a small program that reads in a file and processes the data into a custom data type. The file being read contains lines of data that look like this:
cat 10 20 dog
hamster 12 2 wombat
monkey 1 9 zebra
lion 30 60 rhino
...
My program to process the file looks like this:
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)
My problem is with the processFile
function. Currently, this function only captures the last line of the file and prints it to the screen. I am confused on how to implement recursion with a tuple instead of using append with a list in this function. Can anyone show me how how to fix my function and/or a better implementation of this function? The printed output of this program should be:
[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"}]
Thanks for your time.
Upvotes: 3
Views: 581
Reputation: 183888
You probably intended
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 [] = []
Your first pattern [[a,b,c,d]]
matches only lists with exactly one element, which is a list with exactly four elements.
Upvotes: 8