I am working through this question:
In a four-player game of bridge, each player gets 13 cards, dealt in order.
Write a predicate deal(Cards, H1, H2, H3, H4)
that takes a deck as its first argument, and succeeds by binding H1
to the 13 cards received by player 1 in the deal, etc.
Hint: One strategy is to write four helper predicates deal1
that deals to player
1, deal2
that deals to player 2, etc.
Here is the code given:
cards(ace).
cards(deuce).
cards(three).
cards(four).
cards(five).
cards(six).
cards(seven).
cards(eight).
cards(nine).
cards(ten).
cards(jack).
cards(queen).
cards(king).
suits(spades).
suits(hearts).
suits(clubs).
suits(diamonds).
deck([(ace,spades),(deuce,spades),(three,spades),(four,spades),
(five,spades),(six,spades),(seven,spades),(eight,spades),
(nine,spades),(ten,spades),(jack,spades),(queen,spades),
(king,spades),
(ace,hearts),(deuce,hearts),(three,hearts),(four,hearts),
(five,hearts),(six,hearts),(seven,hearts),(eight,hearts),
(nine,hearts),(ten,hearts),(jack,hearts),(queen,hearts),
(king,hearts),
(ace,clubs),(deuce,clubs),(three,clubs),(four,clubs),
(five,clubs),(six,clubs),(seven,clubs),(eight,clubs),
(nine,clubs),(ten,clubs),(jack,clubs),(queen,clubs),
(king,clubs),
(ace,diamonds),(deuce,diamonds),(three,diamonds),(four,diamonds),
(five,diamonds),(six,diamonds),(seven,diamonds),(eight,diamonds),
(nine,diamonds),(ten,diamonds),(jack,diamonds),(queen,diamonds),
(king,diamonds)]).
Here is my answer:
deal([],[],[],[],[]).
deal([C1,C2,C3,C4|Cards],[C1|H1],[C2|H2],[C3|H3],[C4|H4]) :-
deal(Cards,H1,H2,H3,H4).
I'm almost positive that my answer is correct, but I am having a problem querying.
?- deal(deck,A,B,C,D).
The query comes back fail
, but putting in the actual list of cards, instead of deck
works.
I think the problem is where I'm trying to insert deck, when it's not a list, but I don't know how to get into the list in deck
. I'm new to Prolog, so hopefully it's just a simple fix. Thanks
EDIT:
After adding the suggestion below. My new answer is
dealer([],[],[],[],[]).
dealer([C1,C2,C3,C4|Cards],[C1|H1],[C2|H2],[C3|H3],[C4|H4]) :-
dealer(Cards,H1,H2,H3,H4).
deal(_,A,B,C,D) :-
deck(Deck),
dealer(Deck,A,B,C,D).
The problem, I think, is that deck
is not a list, but a predicate of arity 1 whose sole argument matches a list of all the cards.
Try:
deck(Deck),
deal(Deck,A,B,C,D).
So, you need to get the Deck list out of deck
by calling deck
with an unbound variable, then use that newly bound variable to call deal
.