Haskell IO recursion
I have some code:
read :: IO [Line]
read = do
line <- getLine
let count = length line
line2 <- getLine
if (length line2 /= count)
then error "too long or too short"
else read
What I want to do is based on the length of the first line that the user needs the length of the input - 1 more line, also if any of these lines are not the same length as the original line an error message will appear.
Right now my code is just an endless loop as I cannot figure out how to enter the length of another 1 line. Some advice for this would be appreciated.
Edit: String is of type String
+3
source to share
1 answer
You can use this replicateM
to replicate an action a specific number of times and collect the results. In your case, the action is to grab the string, check its length and error if it is invalid. You can use something like the following to get your work done:
import Control.Monad (replicateM)
read :: IO [Line]
read = do
line <- getLine
let count = length line
lines <- replicateM (count-1) $ do
line <- getLine
if length line /= count
then fail "too long or too short"
else return line
return $ line : lines
+5
source to share