Loop with StateT: Why is this loop not working?

I don’t understand why this code does the loop only once and then exits? in Ghci, I can only respond to the first loop, then it seems that the cont variable is set to false, and I have no invitation to respond.

Result:

*Main> testLoop1 td10
test
Do you want to continue? (y/N)
y
we continue
test
Do you want to continue? (y/N)
We stop

the code:

type TDeckSTIO    = StateT TableDecks IO

continue = do
putStrLn "Do you want to continue? (y/N)"
c <- getChar
return $ c == 'y'


loop1 :: TDeckSTIO () 
loop1 = do 
    liftIO $ putStrLn "test"
    cont<- liftIO continue 
    if cont
    then do 
        liftIO $ putStrLn "we continue"
        liftIO $ testLoop1 td

    else liftIO $ putStrLn "We stop"

testLoop1 td =  runStateT (loop1 ) td   >> return ()
+5
source share
1 answer

The problem is that when you type yand press, enter, after actually typing two characters: 'y'and a newline character, which is sent by pressing the return key. The cycle sees for the first time 'y', but the next time it sees '\n', and since it is '\n'not 'y', it completes the work.

hSetBuffering stdin NoBuffering, ( System.IO), , , , , :

continue = do
  putStrLn "Do you want to continue? (y/N)"
  s <- getLine
  return $ s == "y"

, liftIO $ testLoop1 td : loop1, .

, testLoop1 :

testLoop1 = evalStateT loop1

evalStateT runStateT, , >> return ().

+15

All Articles