I would like to optionally abort the getChar action. I need the following function:
getChar' :: (Char -> IO ()) -> IO (IO ())
In the case of abort <- getChar' callback character is read from standard input, unless abort is called before the character is available. If a character is read, a callback is called with it.
I have the following prototype implementation:
import Control.Monad import Control.Concurrent getChar' :: (Char -> IO ()) -> IO (IO ()) getChar' callback = do v <- newEmptyMVar tid <- forkIO $ do c <- getChar b <- tryPutMVar v () when b $ callback c return $ do b <- tryPutMVar v () when b $ killThread tid
The problem is that killThread can interrupt the thread after reading char, but before putting () in MVar.
I have no idea how to solve this problem, is it even possible with the basic package? If not, have you seen a similar feature implemented in other packages?
io haskell
Péter diviánszky
source share