What is the correct (functional) way to alter a list and return what was
removed?
I'm trying to learn scala, and decided to create a poker app to get my
head around some of the class objects. I've got decks working fine, but
I've got to the point where I need to draw 5 cards. So far I have:
class Deck {
private var deck = newDeck
def draw(amount: Int): List[Card] = {
val ret = deck.take(amount)
deck = deck.drop(amount)
ret
}
def newDeck: List[Card] = {
Random.shuffle((1 to 13).map(x => List(Card(x, "D"), Card(x, "C"),
Card(x, "H"), Card(x, "S"))).toList.flatten)
}
override def toString: String = "Deck has " + deck.length + " cards left."
}
This draw function doesn't seem quite right having two steps - but I'm not
sure how I else I can (or should) take the top however many cards, and
leave the list in a state without those cards in?
(As an aside, if someone has a better function for the deck
creation/shuffle I'm all ears, this seems a bit hacky too... but my main
question is the list state)
No comments:
Post a Comment