2017-03-17 97 views
0

我是Haskell的初學者,我被困在IO問題,我無法解決。Haskell - 比較與字符的IO字符

我正在做一個Snake遊戲,我唯一需要做的事情就是讓用戶輸入,讓蛇移動。因此,這裏是我的功能

--Get char 
input :: IO Char 
input = 
    hSetEcho stdin False 
    >> hSetBuffering stdin NoBuffering 
    >> getChar 

myFunction :: IO Char -> Int -> Int 
myfunction myChar oldValue 
    | (myChar == 'q') = 1 
    | (myChar == 'w') = 2 
    | (myChar == 'e') = 3 
    | (myChar == 'r') = 4 
    | otherwise = oldValue 

-- At the beginning of the game, function is called like this 
let dir = myFunction input 1 --To give the snake an initial direction 

-- The game works with a function Turn that takes an Int as parameter 
-- which is the previous direction. let's call it oldDir 
let newDir = myFunction input oldDir 
-- Then I call Turn again with newDir as parameter 

的問題來自於(myChar ==字符)的一部分,是「無法符合預期的類型‘IO字符’與實際類型‘字符’」

如何比較IO Char和Char?

簡答:我不行。你能幫我解答更長的問題嗎? 這個問題可能被問了很多次,但我仍然堅持這個問題。

預先感謝您的回答!

親切,

+1

我的首選回答是:在C中,'getchar()'等於''L''? –

回答

3

必須擡起比較到IO單子。例如:

myFunction :: Char -> Int -> IO Int 
myFunction 'q' _ = return 1 
myFunction 'w' _ = return 2 
myFunction 'e' _ = return 3 
myFunction 'r' _ = return 4 
myFunction _ x = return x 

-- Actual return type depends on what the function actually does 
someOtherFunction :: Int -> IO ? 
someOtherFunction oldDir = do 
    dir <- input 
    newDir <- myFunction dir oldDir 
    ... 

另一個(可能更好)的選擇是保持myFunction一個純粹的功能,並使用fmap如果你需要將其應用到IO Char

-- Note the change in the argument order 
myFunction :: Int -> Char -> Int 
myFunction _ 'q' = 1 
... 
myFunction x _ = x 

someOtherFunction oldDir :: Int -> IO ? 
    newDir <- fmap (myFunction oldDir) input 
    ...