Haskell -- 并发 I/O 路由
Haskell -- Concurrent I/O Routing
我是 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 流似乎是通过线程循环的。有没有办法让程序读取输入的每一行,而不是每隔一行?
实施总是很重要。原来runJack
在Sound.JACK中调用了waitForBreak
,它的定义是:
waitForBreak :: IO ()
waitForBreak =
let go = getLine >> go
in go
使用 collectInput
解决了问题。
我是 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 流似乎是通过线程循环的。有没有办法让程序读取输入的每一行,而不是每隔一行?
实施总是很重要。原来runJack
在Sound.JACK中调用了waitForBreak
,它的定义是:
waitForBreak :: IO ()
waitForBreak =
let go = getLine >> go
in go
使用 collectInput
解决了问题。