Haskell - How can I get out of the interaction?

I use interactto process some user inputs step by step (in particular, this is a chess program). However, I did not find a way to cope with a situation where the user can simply break out of the cycle and start this chess match from the very beginning.

When I execute the normal procedure in ghci, pressing Ctrl-Cwill not exit the whole ghci, but just stop the procedure and let me continue with some other procedures. However, if I click Ctrl-Cin the console with the function active interact, the following message is displayed:

^CInterrupted.
*Main> 
<stdin>: hGetChar: illegal operation (handle is closed)

And then I need to run ghci again.

I also thought about catching special user inputs such as "exit", however, since the type interactis equal interact :: (String -> String) -> IO (), the input must first go through the function printed (String -> String), and I don’t know, t found a way for this function to notify the main IO that that he should go out.

How do I get out interact? Or is it interactnot intended to be used that way, and should I create custom I / O functions?

+5
source share
1 answer

How do I get out interact?

. interact f getContents >>= putStrLn. f getContents >>= putStrLn. f. getContents stdin. , , .

^ D

readline. GHCi stdin LineBuffer NoBuffering readline. interact ^D, :

ghci> import System.IO
ghci> hGetBuffering stdin
NoBuffering
ghci> hSetBuffering stdin LineBuffering
ghci> interact id
hello world
hello world
pressing control-D after the next RETURN
pressing control-D after the next RETURN
<stdin>: hGetBuffering: illegal operation (handle is closed)

interact , IO?

, . interact , . , ( ):

import Control.Monad (when)

interactLine :: (String -> String) -> IO ()
interactLine f = loop
  where
    loop = do
      l <- getLine
      when (l /= "quit") $ putStrLn (f l) >> loop
+6

All Articles