Reputation: 674
I have a function in Haskell which returns me the successor of a card. I know how to access the card, using list comprehension, but not quite sure how to get the next card, so pos+1. Here is my code:
pCard :: Card->Deck->Card
pCard (K,C) _ = (A,S) --exception for last card
pCard crd pck = head [p | (pos,p) <- (zip [0..51] pck), crd==p]
Upvotes: 3
Views: 940
Reputation: 601
You can make you your Card
type instantiate the Enum
typeclass by deriving Enum
, then use the succ
function to get the successor card.
Note that passing the last card of the deck to succ
will result in a runtime error, though it looks like your first pCard
function body will account for that.
I just noticed that your Card
type appears to be a tuple; I'm guessing you defined Card
using the type
keyword? In which case the solution I proposed above won't work without using GHC extensions.
Upvotes: 3
Reputation: 116139
Hint: use dropWhile (/= crd) pck
to remove all the cards from the beginning until your card is found. Then, the first card remaining is crd
. The one after that is the one you want.
Still, if pck
is a deck in a standard order, looping over the whole deck to find the next card seems to be quite inefficient.
Upvotes: 3