【发布时间】:2014-06-29 15:27:15
【问题描述】:
我一直在尝试编写一个函数,它可以逐个字母地打印出一个字符串,不带引号,并在每个字母之间暂停一点。例如,如果你给它“hello”,它会打印 h,然后等待,e,然后等待,然后 l,然后等待,然后 l,然后等待,o。但是当我尝试使用threadDelay 时,它会在主线程中暂停。所以它会暂停,然后一次打印所有内容。我试图在prints 函数中创建一个新线程,但它不起作用。帮助!
import Control.Concurrent as C
clean :: String -> String
clean s@[c] = s
clean ('"':s)
| last s == '"' = init s
| otherwise = s
clean ('\'':s)
| last s == '\'' = init s
| otherwise = s
clean s = s
prints :: String -> IO()
prints [] = putStrLn " "
prints (x:xs) = do
C.forkIO $ do
putStr $ clean (show x)
C.threadDelay $ 10000
prints xs
main :: IO()
main = do
prints "hello"
【问题讨论】:
-
以下对我有用:
prints = sequence_ . intersperse (threadDelay (10^5)) . map (putStr . return); main = hSetBuffering stdout NoBuffering >> prints "hello". -
@user2407038 : 什么平台?
-
@GaneshSittampalam Windows 和 Mac(在虚拟机中,但这不重要)
标签: multithreading haskell concurrency