为什么我的 IO 没有按顺序执行? [英] Why isn't my IO executed in order?

查看:21
本文介绍了为什么我的 IO 没有按顺序执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了 IO 未按顺序执行的问题,即使在 do 构造中也是如此.

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

在下面的代码中,我只是跟踪剩下的牌,其中牌是一组字符(一个用于花色,一个用于价值),然后不断询问用户已打出哪些牌.我希望 putStr 在每个输入之间执行,而不是像现在这样在最后执行.

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

推荐答案

absz 的回答是正确的,Haskell 的缓冲 IO 是给你带来麻烦的原因.这是重写 doLoop 以获得您正在寻找的效果的一种方法:

absz's answer is correct, Haskell's buffered IO is what's causing you trouble. Here's one way to rewrite your doLoop to have the effect you're looking for:

doLoop xs = do  putStrLn $ show xs
                input <- getLine
                let s:n:_ = input
                doLoop $ remove (s,n) xs

两个变化:使用 putStrLn 附加换行符并刷新输出(这可能是您想要的),并使用 getLine 在输入处抓取一行一次(同样,可能是你想要的).

The two changes: use putStrLn to append a newline and flush the output (which is probably what you want), and use getLine to grab the input a line at a time (again, probably what you want).

这篇关于为什么我的 IO 没有按顺序执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆