Haskell - 并发I / O路由

时间:2017-07-10 02:49:39

标签: haskell io routing jack

我是Haskell的新手,我不确定并发I / O是如何工作的。我正在探索使用JACK音频绑定可以实现的目标。基本上,以下代码(几乎)是功能性的,但每次输入值时我都需要输入两次:

collectInput :: IORef Double -> IO ()
collectInput freq = forever $ do
        putStr ">> "
        hFlush stdout
        f <- getLine
        case readMaybe f of
            Just x -> do 
                putStrLn $ show x
                writeIORef freq x
            Nothing -> do
                 putStrLn "Nada"


main :: IO ()
main = do
    freq <- newIORef 440
    _ <- forkIO $ runJackStuff freq
    collectInput freq

澄清问题:

Input  |  Result            | Output
----------------------------------------

330    | Frequency changes  | ">> 330.0"
440    | Nothing happens    | ""
220.0  | Frequency changes  | ">> 220.0"
550.0  | Nothing happens    | ""
bleh   | Outputs "Nada"     | ">> Nada"
       | Nothing Happens    | ""
foo    | Outputs "Nada"     | ">> Nada"

我不确定,但看起来IO流是通过线程循环的。有没有办法让程序读取每一行输入,而不是每一行?

1 个答案:

答案 0 :(得分:0)

实施总是很重要。事实证明,runJack在Sound.JACK中调用waitForBreak,其定义如下:

 waitForBreak :: IO ()
 waitForBreak =
     let go = getLine >> go
     in  go

在其位置使用collectInput解决了问题。