How to assert a tuple in a conditional

Given the tuple:

let tuple = (true, 1)

How to use this tuple in conditional expression? Something like that:

if tuple.first then //doesnt work

or

if x,_ = tuple then // doesnt work

I do not want to do this:

let isTrue value = 
   let b,_ = value
   b

if isTrue tuple then // boring

Is there a good way to evaluate the value of a tuple inside a conditional expression without creating a separate function?

+3
source share
3 answers

Function fstcan help you here.

Returns the first element of a tuple

Example:

let tuple = (true, 1)
if fst tuple then
    //whatever

For the second element also exists snd.

Another alternative is to use pattern matching :

let tuple = (true, 1)

let value = 
    match tuple with
    | (true, _) -> "fst is True"
    | (false, _) -> "fst is False"

printfn "%s" value

This allows you to map more complex scenarios, a very powerful construct in F #. Take a look at Tuple's template

+7
source

The function you are looking for is "fst".

let v = (true, 3)
if fst v then "yes" else "no"

"fst" . "snd" .

MSDN .

+3

fst:

if tuple |> fst then
    ...
+2

All Articles