Haskell - 将IO Char与char

时间:2017-03-17 14:58:03

标签: haskell

我是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 == char)部分,并且“无法将预期类型'IO Char'与实际类型'Char'匹配”

如何将IO Char与Char进行比较?

简答:我做不到。你能帮我解决更长的答案吗? 这个问题可能被问了很多次,但我仍然坚持这个问题。

提前感谢您的回答!

亲切地,

1 个答案:

答案 0 :(得分:3)

你必须将比较提升到IO monad。例如:

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 ...

const blob = new Blob([B64A.decode(pdfdata)], {type: 'application/pdf'});
dataURL = (window.URL || window.webkitURL).createObjectURL(blob);