简体   繁体   中英

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

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.

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, eg) include words for splitting a String on whitespace into a list of String s, 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 ma given an a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM