gpt4 book ai didi

loops - Haskell - 我如何摆脱互动?

转载 作者:行者123 更新时间:2023-12-04 14:56:28 24 4
gpt4 key购买 nike

我正在使用 interact逐步处理一些用户输入(具体来说,它是一个国际象棋程序)。但是,我还没有找到一种方法来处理用户可能只想跳出循环并从头开始这场国际象棋比赛的情况。

当我在 ghci 中执行正常程序时,按 Ctrl-C不会退出整个 ghci,但只会停止程序本身并允许我继续执行其他一些程序。但是,如果我按 Ctrl-C在带有 interact 的控制台中函数生效,显示以下消息:

^CInterrupted.
*Main>
<stdin>: hGetChar: illegal operation (handle is closed)

然后我必须重新启动 ghci。

然而,我也想过捕捉特殊的用户输入,例如“退出”,因为 interact 的类型是 interact :: (String -> String) -> IO () , 输入必须通过类型为 (String -> String) 的函数首先,我还没有找到一种方法让该函数通知主 IO 它应该退出。

我应该如何突破 interact ?或者是 interact不打算以这种方式使用,我应该编写自定义 IO 函数?

最佳答案

How should I break out of interact?



你不能。你可以想到 interact fgetContents >>= putStrLn . f .和 getContents将关闭 stdin 上的句柄.任何有关读取的进一步操作都将失败。

The literal character ^D gets shown in the terminal



那是readline的问题。 GHCi改变 stdin的缓冲方式来自 LineBufferNoBuffering以最佳方式使用 readline。如果要退出 interact^D ,则需要更改缓冲方法:
ghci> import System.IO
ghci> hGetBuffering stdin
NoBuffering
ghci> hSetBuffering stdin LineBuffering
ghci> interact id
hello world
hello world
pressing control-D after the next RETURN
pressing control-D after the next RETURN
<stdin>: hGetBuffering: illegal operation (handle is closed)

Or is interact not intended to be used this way and I should compose custom IO functions?



是的,它不打算以这种方式使用。 interact旨在使用所有输入并指示所有输出。如果要使用逐行输入,可以编写自己的逐行交互方法(或使用外部库):
import Control.Monad (when)

interactLine :: (String -> String) -> IO ()
interactLine f = loop
where
loop = do
l <- getLine
when (l /= "quit") $ putStrLn (f l) >> loop

关于loops - Haskell - 我如何摆脱互动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37205740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com