skyw00lker
skyw00lker

Reputation: 819

change of conditions in recursive function

First of all this is an assignment so I don't want a complete solution :)

I'm going to calculate the value of a deck in the Cardgame blackjack.

Rules are all Aces are 1 or 11.

suppose my hand is: (Ace, 5), My hand is now 16. Next card is a 6, my hand is now (Ace, 5,6) 22 but the ace that I already calculated before must now change to one so my hand is at 12.

my Hand datatype is defined recursive by

data Hand = Empty | Add Card Empty

so calculate a hand with fixed values are done by

valueOfHand (Add c h) = cardValue c + valueOfHand h

What's the pattern to change the values that appeared before?

Upvotes: 2

Views: 110

Answers (2)

shang
shang

Reputation: 24822

I'm not sure if your class has already covered the list monad, but I think that's the most natural way to solve this. So instead of having cardValue return a simple value, it should return a non-deterministic value that lists all the possible values that the card might have, i.e.

cardValue :: Card -> [Int]
cardValue Ace = [1, 11]
cardValue Two = [2]
...

valueOfHand will then have two parts: one that computes a list of all possible hand values and another that selects the best, legal hand.

Let me know if this is enough for you to solve it or if you need more hints.

Upvotes: 1

C. Quilley
C. Quilley

Reputation: 1059

If, as you indicate in the comments, Aces may only have one value per hand (so a hand of three Aces is 3 or 33), then it makes sense to define your valueOfHand :: Hand -> Integer function in a way that first totals up non-Ace cards and then handles the Aces.

I would expect such a function would be based around something like this:

valueOfHand Empty = 0

valueOfHand h = valueOfAces (filter (\c -> c == Ace) h) (filter (\c -> c /= Ace) h)

For some function valueOfAces :: Hand -> Hand -> Integer.

Upvotes: 0

Related Questions