Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 946
gdrules Avatar asked Jun 06 '26 07:06

gdrules


1 Answers

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
like image 89
Lily Ballard Avatar answered Jun 08 '26 21:06

Lily Ballard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!