Reputation: 123
I am trying to access the fst element of a tuple. Normally I use fst (tuple), but this situation is a little different.
let getCard (pl : player) : (card * player) option =
let plDeck = pl
match plDeck with
| c1::re -> Some (c1,(re))
| [] -> None
This is my f# code. the player type is a list of ints
, and the output is tuple with the first int
of the player list, and the player list minus the first int
.
It's an assignment from my computer science class, so it is required that I use the option type.
I am trying to access the fst
element of the tuple in another function by writing
let gc = fst (getCard [1,2,3])
but it seems like I can't do it this way, since I am getting the warning:
This expression was expected to have type ''a * 'b' but here has type '(card * player) option'
How do I work around this?
Upvotes: 2
Views: 253
Reputation: 36
The compiler is telling you that you're trying to access an option of tuple card * player while the function fst expects a tuple of card * player.
You could pattern match on your getCard function and extract the card.
let result =
match getCard [1..5] with
| Some card -> fst(card)
| None -> -1
You could also use pattern matching to extract the first part of your tuple.
let result =
match getCard [1..5] with
| Some (card, _) -> card
| None -> -1
As suggested by @Guran you shouldn't return magic numbers
let result =
match getCard [1..5] with
| Some (card, _) -> Some card
| None -> None
Upvotes: 1