Alex
Alex

Reputation: 667

Haskell Blackjack game

Hi i'm having problems summing my hand up since an Ace can be 1 or 11. How can I make a function which takes in a hand, ie [Card] and calculates the total value?

Here is what I have so far:

handValue :: [Card]->[Int]
handValue [] = 0
handValue (x:xs) = sum((val x)++([handValue xs]))

where val is already defined and returns from a card an array of values. eg val ("Ace","Hearts") gives [1,11] val ("Five","Hearts") gives [5]

Any pointers would be appreciated.

edit: after duplodes suggestion I have this:

    handValue :: [Card]->[Int]
handValue [] = 0
handValue (x:xs) = 
            if (val x ==[1,11])
            then    (map sum (sequence [[1,11], handValue xs]))
                else [ sum [(val x)]++([handValue xs])]

Upvotes: 0

Views: 1145

Answers (2)

duplode
duplode

Reputation: 34398

Beyond fixing your function you should pay attention to why it didn't work in first place. Firstly, the type you gave is

handValue :: [Card] -> [Int]

but your recursive definition has single values, and not lists, as result types (the 0 literal in the first equation; the use of sum, which is Num a => [a] -> a in the second one).

Now, assuming the type was changed to [Card] -> Int, your definition would be legal, but the results would be weird. Your second equation is:

handValue (x:xs) = sum((val x)++([handValue xs]))

What happens if x is an ace? val x will be [1, 11], and so both values will be concatenated and included in the sum. In effect, your aces now count not as 1 or 11, but 12 points! n.m's solution, which I paraphrase here as

Prelude> map sum . sequence $ [[1,11], [5], [6]]
[12,22]

skirts around the problem by generating lists of values for all possible choices of aces (sequence) and summing all possibilities separately (map sum), resulting in a list of values (as in the signature you had originally given). That, however, does not quite settle the issue, as you will eventually need to decide for one of the possibilities. And now we likely have enough material for a different question, once you get to that point...

Upvotes: 1

n. m. could be an AI
n. m. could be an AI

Reputation: 120051

Prelude Control.Monad> liftM sum . sequence $ [[1,11], [5], [6]]
[12,22]

Upvotes: 1

Related Questions