0

Assume i have something like this

main = do
    input_line <- getLine
    let n = read input_line :: Int

    replicateM n $ do
        input_line <- getLine
        let x = read input_line :: Int 

        return ()

 ***putStrLn $ show -- Can i access my replicateM here?
    return ()

Can i access the result of my replicateM such as if it was a returned value, and for example print it out. Or do i have to work with the replicateM inside the actual do-block?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
JohEker
  • 627
  • 5
  • 13
  • 1
    `readLn` is superior to `getLine`+`read`, because it throws an `IO` error immediately if you get text that isn't `read`able rather than waiting until some indeterminate later date when the value is used to throw an exception. – Daniel Wagner Jun 03 '18 at 00:25

3 Answers3

4

Specialized to IO

replicateM :: Int -> IO a -> IO [a]

which means that it returns a list. So in your example you could do:

results <- replicateM n $ do
    input_line <- getLine
    let x = read input_line :: Int
    return x   -- <- we have to return it if we want to access it

print results
luqui
  • 59,485
  • 12
  • 145
  • 204
3

replicateM n a returns a list of the values returned by a. In your case that'd just be a list of units because you have the return () at the end, but if you replace that with return x, you'll get a list of the read integers. You can then just use <- to get it out of the IO.

You can also simplify your code by using readLine instead of getLine and read. Similarly putStrLn . show can be replaced with print.

main = do
    n <- readLn
    ints <- replicateM n readLn :: IO [Int]
    print ints
sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

Of course. Its type is replicateM :: Monad m => Int -> m a -> m [a]. It means it can appear to the right of <- in a do block:

    do
        ....
        xs <- replicateM n $ do { ... }
        ....

xs will be of type [a], as usual for binding the results from Monad m => m [a].

With your code though, where you show return () in that nested do, you'll get ()s replicated n times in your xs. Presumably in the real code you will return something useful there.

Will Ness
  • 70,110
  • 9
  • 98
  • 181