0

I've finished writing a Haskell program but I have troubles with the I/O and Main parts of it. I want to read input of the following format:

10 3
1 4 8

The first and second numbers are Ints, and the numbers of the second line should be made into an integer list, [Int]. The length of the list is equal to the second number on the first line.

I have the following code to read one Int at a time, however, it can only get it to work for the first line of input.

getInt :: IO Int
getInt = do
    l <- getLine
    return (read l) 

What am I doing wrong?

5
  • 1
    have a look at the words function - something like map read . words should work for you Commented Mar 13, 2016 at 13:44
  • 1
    BTW: I am a bit surprised that you claim that you function works on "10 3" - I would have expected this to give you an no parse error Commented Mar 13, 2016 at 13:46
  • I do get a no parse error, although I thought that stemmed from the second input line and an end-of-file-related error. Commented Mar 13, 2016 at 13:54
  • no - it's because you try to read in two numbers at once - but you can use the map read . words I talked about - you can patternmatch as well if you like: [x, y] <- map read . words <$> getLine should do the trick here for the first line - you get the second (in a list) by just numbers <- map read . words <$> getLine (all in a do block of course!) Commented Mar 13, 2016 at 14:45
  • Extremely helpful. Thank you very much! Commented Mar 13, 2016 at 14:53

1 Answer 1

1

you should be able to get the data shown here by:

readData :: IO (Int, [Int])
readData = do
    [nr, _] <- map read . words <$> getLine
    nrs     <- map read . words <$> getLine
    return (nr,nrs)

this will read both lines and return the 10 as the first component and [1,4,8] as the second component of a tuple if you read in your example

As the second number in the first line will just be the length of the returned list I skipped it here.

of course you probably will want to adapt this to your needs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.