Haskell - splitting a list of strings into a tuple of the form (String, [Int])

时间:2017-04-10 01:29:33

标签: string haskell io tuples

Is there a way to do this? I'm writing a small program to read in a list of students of the form c1234501 10 20 10 30 30, and making it searchable via the string at the beginning, and displaying the averaged sum of the values behind it.

I'm currently reading in the file and splitting it into a list of strings via the following code:

main = do
    putStrLn "Filename?"
    fileName <- getLine
    inputFile <- openFile fileName ReadMode
    contents <- hGetContents inputFile
    let lineList = lines contents
    let studentStrings = tail lineList

However, I'm running into an error with the last line, saying that i have a type mismatch between String and IO String.

I'm also at a loss as to how to write a function to convert the string lists into tuples of the form (String, [Int]). I feel confident that this is my only sticking point; I think I can probably get the rest of it on my own.

1 个答案:

答案 0 :(得分:2)

I won't give you code, because you should be able to work this out on your own given a bit of direction. Some functions you should look into (on hoogle, e.g.) include words for splitting a String on whitespace into a list of Strings, and read for converting a String into (in your case) an Int. You'll want to look into fmap or map to understand how to apply a function to every element in a list. Finally, re the type mismatch between String and IO String, you need pure or return - these are used to obtain an m a given an a.