Kamsiinov
Kamsiinov

Reputation: 1490

F# add values to existing list

Continuing with the series of creating card game with F#. Now I am stuck with adding values to list of cards. I have

type Player = {Name : String; Hand : Card list}

I am able to get the card from the deck and it works well. I can also create new list with

let player = {Name = "Player"; Hand = List.Empty}
let testlist = List.append player.Hand anotherlist

But I cannot figure out how to put add the anotherlist directly to players hand.

Upvotes: 3

Views: 178

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

You can use the with construct:

let playerWithHand = { player with Hand = testlist }

As records in F# are immutable, you do not typically mutate an existing record (although there are ways to do that too) and instead, you create a new value representing the new state of the player. The with keyword makes this very easy, because it clones a record and changes some of its properties to new values as specified.

Upvotes: 7

Related Questions