Reputation: 331
i have a haskell function, somehow related to infix operators.
(<+) :: Hand -> Hand -> Hand
Empty <+ hand = hand
hand <+ Empty = hand
(Add card hand1) <+ h2 = Add card (hand1 <+ h2)
The first two lines after the function signature are pretty understandable but the last one is a bit hard for me to understand how it flow
The purpose of the function is to create an operator that when given two hands, it adds one hand onto the other. By "Hand" i can mean a collection of cards.
The definition of card and Hand types is as follows
data Card = Card { rank :: Rank, suit :: Suit } deriving (Eq, Show)
data Hand = Empty | Add Card Hand deriving (Eq, Show)
Upvotes: 0
Views: 102
Reputation: 52280
The last one is the usual recursive case:
If your left hand consists of one card card
plus some tail-hand hand1
then you can concatenate your right hand h2
(naming seems strange) by adding card
in front of what you get when you you concatenate hand1
and h2
(recursivley) - which is exactly hand1 <+ h2
The important thing is that the left-hands get smaller so the recursion can finally stop - you just push (<+)
deeper in there (by pulling Add
out) till you get to one of the Empty
-cases.
Maybe an example helps:
(Add l1 (Add l2 Empty)) <+ (Add r1 Empty)
{ last case }
= Add l1 ((Add l2 Empty) <+ (Add r1 Empyt))
{ last case for the inner part }
= Add l1 (Add l2 (Empty <+ (Add r1 Empty)))
{ first case inner }
= Add l1 (Add l2 (Add r1 Empty))
which is just a hand with l1,l2,r1
(or so I guess)
Upvotes: 5