Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# pattern matching with tuples rule will never be matched

First off I'm new to f#, so maybe the answer is obvious, but I'm not seeing it. So I have some tuples with an id, and a value. I know the id that I'm looking for and I want to select the correct tuple out of three that I'm passing in. I was going to do this with two match statements one nested in the other, but every thing is matching with the first rule. For this example I cut it down to two tuples since this shows my issue. The compiler is giving a "rule will never be matched" warning, but I don't see why.

let selectTuple tupleId tuple1 tuple2 = 
    match tuple1 with
    | (tupleId, _) -> tuple1
    | _ -> tuple2

Any help or suggestions on a better way to do this would be greatly appreciated.

like image 319
Jesse Avatar asked Jan 25 '17 19:01

Jesse


People also ask

What does ⟨F⟩ mean?

This sound is usually considered to be an allophone of /h/, which is pronounced in different ways depending upon its context; Japanese /h/ is pronounced as [ɸ] before /u/. In Welsh orthography, ⟨f⟩ represents /v/ while ⟨ff⟩ represents /f/. In Slavic languages, ⟨f⟩ is used primarily in words of foreign (Greek, Latin, or Germanic) origin.

What does the letter F mean in math?

In countries such as the United States, the letter "F" is defined as a failure in terms of academic evaluation. Other countries that use this system include Saudi Arabia, Venezuela, and the Netherlands. In the hexadecimal number system, the letter "F" or "f" is used to represent the hexadecimal digit fifteen (equivalent to 15 10 ).

What does F stand for in the Etruscan alphabet?

In the Etruscan alphabet, 'F' probably represented /w/, as in Greek, and the Etruscans formed the digraph 'FH' to represent /f/.

Is the letter F doubled at the end of words?

It is often doubled at the end of words. Exceptionally, it represents the voiced labiodental fricative / v / in the common word "of". F is the twelfth least frequently used letter in the English language (after C, G, Y, P, B, V, K, J, X, Q, and Z ), with a frequency of about 2.23% in words.


1 Answers

Use a when clause:

let selectTuple tupleId tuple1 tuple2 = 
    match tuple1 with
    | (x, _) when x = tupleId -> tuple1
    | _ -> tuple2

What is happening here is that when you use tupleId as part of the match case, you introduce a new value called tupleId that you can refer to on the right side of the match case. This shadows your function argument.

Since you're effectively only giving a name to the first element of a tuple, any tuple will match the first case, and that's how you get 'rule won't be matched' warning on the second one.

like image 178
scrwtp Avatar answered Oct 06 '22 16:10

scrwtp