我需要为我的期末学习项目编写一个简单的蛇游戏,但是我被困在最后一个功能上。我想我真的不知道如何完美地使用数据结构。函数doInstruction
应该为此测试用例doInstruction (Turn East) (North, [(5, 7), (5, 6)], 2) == (East, [(5, 7), (5, 6)], 2)
回报True。
我的代码:
data Dir = West
| North
| East
| South deriving (Eq, Show)
type Position = (Int, Int)
type Snake = (Dir, [Position], Int)
data Instruction = Move | Turn Dir deriving (Eq, Show)
isOppositeDir :: Dir -> Dir -> Bool
isOppositeDir West East = True
isOppositeDir East West = True
isOppositeDir North South = True
isOppositeDir South North = True
isOppositeDir _ _ = False
oppositeDir :: Dir -> Dir
oppositeDir West = East
oppositeDir East = West
oppositeDir North = South
oppositeDir South = North
nextPos :: Dir -> Position -> Position
nextPos x (a,b)
| x == West = (a - 1 , b)
| x == East = (a + 1 , b)
| x == North = (a , b + 1)
| x == South = (a , b - 1)
| otherwise = (a , b)
doInstruction :: Instruction -> Snake -> Snake
doInstruction ins s
| ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
我得到的错误:
E:\\ELTE\2019_1_Funkcprog\hf13.hs:34:19: error:
Data constructor not in scope: Dir :: Dir
|
34 | | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
| ^^^
E:\\ELTE\2019_1_Funkcprog\hf13.hs:34:38: error:
Data constructor not in scope: Dir :: Dir
|
34 | | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
| ^^^
E:\\ELTE\2019_1_Funkcprog\hf13.hs:34:44: error:
Data constructor not in scope: Position :: Position
|
34 | | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
| ^^^^^^^^
E:\\ELTE\2019_1_Funkcprog\hf13.hs:34:63: error:
Data constructor not in scope: Position
|
34 | | ins == Turn Dir = (oppositeDir Dir, [Position], length [Position])
| ^^^^^^^^
答案 0 :(得分:3)
您需要使用模式匹配来“解压缩”数据构造函数。 Haskell中的变量以小写开头。因此,我们可以打开Instruction
对象和代表蛇的3元组的包装:
doInstruction :: Instruction -> Snake -> Snake
doInstruction (Turn dir) (_, p, l) = (dir, p, l)