I need to enter the size of the array into the console, and then fill it with elements.

For example, I drive:


five


1 2 3 4 5


Here, for example, I enter the size

main :: IO() main = do n1 <- readLn 

And here I have already not found how to enter elements, such a function as getLine introduces a line, not integers

  • You need to break this line into spaces on the list, and then apply read :: String -> Int to each element. As a result, get a list of integers. - arrowd

1 answer 1

To break a string into words separated by spaces, use the words function, then each word can be converted to a number using the read function:

 main :: IO() main = do numbers <- map read . words <$> readLn 

Note, however, that the read function is a partial function. This means that if any part of the input string is not a number, your program will crash. If your question is related to homework or a one-time script, then that's okay. However, if you are writing something long-term, I would recommend using safer counterparts, such as readMaybe .

Also note that the read function needs to know the output type. In your case, this type, apparently, should be Int . But this type is not specified anywhere. If the numbers list is subsequently passed to another function whose type is specified, the compiler will take the type from there, for example:

 printNums :: [Int] -> IO () printNums = print main :: IO() main = do numbers <- map read . words <$> readLn printNums numbers 

However, if you try to call the print function without specifying a type, then your program will not compile:

 main :: IO() main = do numbers <- map read . words <$> readLn print numbers -- ERROR: ambiguous type 
  • Only here arrays are not used, as the author wrote. You can enter a list of a different size than entered from the console. - arrowd