Complexity in Haskell with recursive tuple function

I have a small program that reads in a file and processes 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 for processing 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 function processFile

. 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 someone show me how to fix my function and / or improve the 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"}]

      

Thank you for your time.

+3


source to share


1 answer


You probably planned

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]]

only matches lists with exactly one element, which is a list with exactly four elements.

+8


source







All Articles