Dany
Dany

Reputation: 3

How to write a function in Haskell that returns all combinations of 5-card hands than can be taken from a given deck of cards

I'm not very experienced with programming and I have a problem that I can't seem to figure out. I have the types:

newtype Hand = Hand { unHand :: [Card] } deriving (Eq, Show)
type Deck = [Card]

I want to write a function allHands such that it returns all possible combinations of 5 cards that can be taken from a given deck.

allHands :: Deck -> [Hand]  
allHands deck = combs 5 deck 

where combs :: Int -> [a] -> [[a]] is a function I made that returns all the possible combinations that can be formed by taking n elements from a list.

My function doesn't work because the result of my function (combs 5 deck ) is [[Card]] and I want it to be [Hand]. Can anyone help me with this?

Upvotes: 0

Views: 543

Answers (2)

karakfa
karakfa

Reputation: 67467

Using Data.List subsequences

allHands = filter ((5==).length) . subsequences

Upvotes: 0

user2297560
user2297560

Reputation: 2983

You almost have it.

allHands deck = map Hand (combs 5 deck)

Here's my original answer which probably doesn't do what you want (because it generates duplicates):

import Data.List (permutations)

allHands = map Hand . map (take 5) . permutations

Upvotes: 2

Related Questions