我是Haskell的初学者,我陷入了一个无法解决的IO问题中。
我正在做一款蛇游戏,我唯一需要做的就是接受用户的输入来让蛇移动。这是我的功能
--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)部分,“无法将预期类型‘myChar’与实际类型‘Char’匹配”。
如何比较IO Char和Char?
简短的回答:我做不到。你能帮我拿一下更长的答案吗?这个问题可能被问了很多次,但我仍然被困在这个问题上。
提前谢谢你的回答!
真诚地,
发布于 2017-03-17 15:04:59
您必须将比较提升到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保持为纯函数,如果需要将其应用于IO Char,则使用fmap。
-- 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
...https://stackoverflow.com/questions/42860743
复制相似问题