Reputation: 87
I need to write a simple snake game for my final school project but i got stuck on my last function. I guess I don't really know how to use the datastructures perfectly. The funcition doInstruction
should give back True for this testcase doInstruction (Turn East) (North, [(5, 7), (5, 6)], 2) == (East, [(5, 7), (5, 6)], 2)
What am I doing wrong?
My code:
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])
The errors I get:
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])
| ^^^^^^^^
Upvotes: 4
Views: 442
Reputation: 477265
You need to use pattern matching to "unpack" the data constructor. Variables in Haskell start with a lowercase. We thus can unpack the Instruction
object, and the 3-tuple that represents the snake:
doInstruction :: Instruction -> Snake -> Snake
doInstruction (Turn dir) (_, p, l) = (dir, p, l)
Upvotes: 3