F # correspond to the opposite value

I need a simple function that gives the opposite value - return v2, if v == v1; return v1 if v == v2. I tried the following:

let oppose v v1 v2 =
    match v with
    | v1 -> v2
    | v2 -> v1
    | _ -> ""

But I get warnings:

warning FS0026: This rule will never be matched
warning FS0026: This rule will never be matched

And this does not work as expected:

> oppose "a" "a" "b"
val it : string = "b"
> oppose "b" "a" "b"
val it : string = "b"

I would expect to get an "a" in the second call. What am I doing wrong?

+4
source share
1 answer

The names used in the match clause are the names assigned to the result, not the value check. You need to explicitly check:

let oppose v v1 v2 =
    match v with
    | a when a = v1 -> v2
    | b when b = v2 -> v1
    | _ -> ""

You can also use ifinstead of matching. It might be easier to read if you are checking the values, as in this case:

let oppose v v1 v2 =
    if v = v1 then v2
    elif v = v2 then v1
    else ""
+3
source

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


All Articles