Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# how to add type to list?

Tags:

f#

So I am trying to create a card game for school project with F#. I am coming from C# and having problems in understanding stuff in F#. I have type

Player = {Name : String; Hand : Card list} which represents the player

then I have deck which has cards inside. How can I move the first card from the deck to players hand? In C# I would be using something like removeat[i].

like image 818
Kamsiinov Avatar asked Mar 09 '23 00:03

Kamsiinov


1 Answers

let returnFirstElement list =
  match list with
  | h::t -> Some(h),t
  | [] -> None,[]

Pass your list into this and it will return a tuple. The first value will be your card, the second is the rest of the deck. The use of Some and None is there as if you run out of cards in your deck then you will not get a card back. As you are from a C# background think of Some as a nullable type and None as null. Look into F# Some and None if you are unsure it is pretty common to use them.

You can use this like

 let (topCard, restOfDeck) = returnFirstElement deckOfCards

Can give you more assistance if needed but that should be a good enough start.

like image 163
NPhillips Avatar answered Mar 27 '23 23:03

NPhillips