1
votes

I want to build a matrix in a list comprehension. For each row I need to getLine and parse it out.

In short, I want to do something like this.

fun = [ getLine | y <- [0..4]]

If I run this function, instead of trying to getLine from command prompt for each row, I get an error for No Instance for (Show (IO String)) arising from a use of 'print'.

I get the error message, but how do I getLine within a list comprehension?

1
You just did use getLine within a list comprehension :P - user253751
Yeah, I really want to use list comprehension so I can get coordinates for a matrix I will build. - mac10688

1 Answers

8
votes

If you’d like to take a list of actions, evaluate each one in sequence, and return each result – [IO a] -> IO [a] – there’s sequence:

fun = sequence [getLine | y <- [0..4]]

and this can be simplified to Control.Monad.replicateM:

fun = replicateM 5 getLine