【发布时间】:2020-12-26 09:06:59
【问题描述】:
我的 haskell 代码有点问题:
import Prelude
hangman :: String -> IO ()
hangman [] = return ()
hangman s = do putStr ("Secret: " ++ text s ++ "\n")
putStr "Enter a character: "
charr <- getChar
function s charr (text s)
function :: String -> Char -> String -> IO ()
function [] _ _ = return ()
function (a:bc) charr (g:jt) = do putStr ("Secret: " ++ (textBack (a:bc) charr (g:jt)) ++ "\n")
putStr "Enter a character: "
charbaby <- getChar
putStr "\n"
function (a:bc) charbaby (textBack (a:bc) charbaby (g:jt))
text :: String -> String
text [] = ""
text (x:ys) = "*" ++ text ys
textBack :: String -> Char -> String -> String
textBack [] _ _ = ""
textBack (a:bc) charr (g:jt) = if charr == a
then charr : textBack bc charr jt
else g : textBack bc charr jt
这是输出:
*Main> hangman "hello"
Secret: *****
Enter a character: h
Secret: h****
Enter a character:
Secret: h****
Enter a character: e
Secret: he***
Enter a character:
Secret: he***
Enter a character: l
Secret: hell*
Enter a character:
Secret: hell*
Enter a character: o
Secret: hello
Enter a character:
Secret: hello
Enter a character:
如您所见,有些行被多次调用,我不知道为什么。 我希望你能帮助我:)
谢谢,
芬恩
【问题讨论】:
-
为什么在
hangman和function中重复逻辑? -
之所以这样做是因为
getChar带一个字符,但是enter也是一个字符。 -
@WillemVanOnsem 在第一次调用中它是一个不同的秘密字符串
-
@WillemVanOnsem 该死的谢谢。我永远不会想到这一点。但是我该如何解决这个问题?
-
@Finn 你可以改用
getLine来修复它,它读取整行而不是字符串。