gdrules
gdrules

Reputation: 329

Haskell IO Recursion

I have the 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 the user has to input length-1 more lines, also if any of those lines are not the same length as the original line, an error message will be displayed.

Right now my code is just an infinite loop as I can't quite figure out how to input length-1 more lines. Some guidance for this will be appreciated.

Edit: Line is of type String

Upvotes: 3

Views: 841

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185861

You can use replicateM to replicate an action a set number of times and collect the results. In your case that action is to grab a line, test its length, and error if it's invalid. So you can use something like the following to accomplish your job:

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

Upvotes: 5

Related Questions