Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

haskell - Why isn't my IO executed in order?

I got a problem with IO not executing in order, even inside a do construct.

In the following code I am just keeping track of what cards are left, where the card is a tuple of chars (one for suit and one for value) then the user is continously asked for which cards have been played. I want the putStr to be executed between each input, and not at the very end like it is now.

module Main where
main = doLoop cards
doLoop xs = do  putStr $ show xs
                s <- getChar
                n <- getChar
                doLoop $ remove (s,n) xs
suits = "SCDH"
vals = "A23456789JQK"
cards = [(s,n) | s <- suits, n <- vals]
type Card = (Char,Char)
remove :: Card -> [Card] -> [Card]
remove card xs = filter (/= card) xs
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the problem is what I think it is, your problem is that Haskell's IO is buffered: this question explains what's happening. When you run a compiled Haskell program, GHC stores output in the buffer and only periodically flushes it to the screen; it does so if (a) the buffer is too full, (b) if a newline is printed, or (c) if you call hFlush stdout.

The other problem you may be seeing is that getChar may not fire until a newline is read, but then the newline is in your input stream; you could perhaps solve this with an extra getChar to swallow the newline, but there should probably be a better way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...