Matching F # patterns to a tuple rule will never be consistent

Firstly, I'm new to f #, so maybe the answer is obvious, but I don't see it. So I have some tuples with id and value. I know the identifier I'm looking for, and I want to select the correct tuple from the three that I pass. I was going to do this with two conformance statements, one nested in the other, but it all depends on the first rule. In this example, I reduced it to two tuples, as this shows my problem. The compiler gives a warning โ€œthe rule will never matchโ€, but I donโ€™t understand why.

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

Any help or suggestions on the best way to do this would be greatly appreciated.

+6
source share
1 answer

Use the when clause:

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

What happens here is that when you use tupleId as part of the match case, you enter a new value called tupleId , which you can refer to on the right side of the match case. This reduces the argument of the function.

Since you actually just provide a name for the first element of the tuple, any tuple will correspond to the first case, and how you get a warning โ€œthe rule will not matchโ€ on the second.

+6
source

Source: https://habr.com/ru/post/1014424/


All Articles