I am learning Haskell with the help of “Learn You a Haskell for Great Good!” and am currently trying to understand typeclasses and instances.
LYAH provides an example where a type called TrafficLight is defined as follows:
data TrafficLight = Red | Yellow | Green
Now TrafficLight is supposed to be an instance of Eq displaying the following behaviour:
instance Eq TrafficLight where
Red == Red = True
Green == Green = True
Yellow == Yellow = True
_ == _ = False
In order to understand how this works, I wrote my own file called Shop.hs where I try to override the behaviour of Eq for my ItemSlot.
module Shop where
type Number = Int
data Item =
BellPepper
| Cabbage
| Carrot
| Lettuce
| Onion
| Potato
| Tomato
deriving (Show, Read, Eq)
data ItemSlot = ItemSlot {
item :: Item,
number :: Number
} deriving (Show)
instance Eq ItemSlot where
((item a) == (item a)) = True -- line that contains the error
_ == _ = False
However, if I load the file in GHCi, I get the following error:
Prelude> :l Shop.hs
[1 of 1] Compiling Shop ( Shop.hs, interpreted )
Shop.hs:21:11: Parse error in pattern: item
Failed, modules loaded: none.
(I must admit that I am rather confused as to what the correct syntax is here – is it item a or just item?
Using only item fails with the same error, and using more parentheses – as was the answer in another question like this on SO – does not seem to help either.)
My guess is that I cannot use the item function provided by the record-syntax that is used in ItemSlot, but nevertheless I do not know how to resolve the issue.
Patterns typically begin with a constructor. The constructor for the
ItemSlottype isItemSlot, so you would use that:Alternately, because you’ve defined
ItemSlotas a record, there’s so-called record syntax for patterns. You can bind variables by name rather than position:You can of course shadow names, if you don’t mind a chance of confusion:
For convenience, patterns in Haskell can be nested; so, if you wanted to match
ItemSlots that both hadBellPeppers, for example, you could writethough usually you would delegate the comparison of
Item‘s to theEqinstance forItems.