Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assert a tuple in conditional

Tags:

f#

Given the tuple:

let tuple = (true, 1)

How do i use this tuple in a conditional? Something like this:

if tuple.first then //doesnt work

or

if x,_ = tuple then // doesnt work

I don't want to do this:

let isTrue value = 
   let b,_ = value
   b

if isTrue tuple then // boring

Is there a nice way to evaluate a tuple value inside a conditional without creating a seperate function ?

like image 851
Paul Nikonowicz Avatar asked Mar 27 '26 19:03

Paul Nikonowicz


2 Answers

The fst function can help you out here.

Return the first element of a tuple

An example:

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

There's also an snd for the second element.

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 can let you match on more complex scenarios, a very powerful construct in F#. Take a look at the Tuple Pattern in the MSDN Documentation for a few examples.

like image 57
vcsjones Avatar answered Mar 30 '26 10:03

vcsjones


The function you are looking for is "fst".

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

"fst" will get the first half of a tuple. "snd" will get the second half.

For additional information, the MSDN has information here.

like image 35
Gary McConnell Avatar answered Mar 30 '26 08:03

Gary McConnell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!