Search code examples
haskellfunctional-programmingmonadsdo-notation

Can we access the output from a replicateM defined in a do-block


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?


Solution

  • 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