我想要一个给出相反值的简单函数 - 如果v == v1则返回v2;如果v == v2,则返回v1。我尝试了以下方法:
let oppose v v1 v2 =
match v with
| v1 -> v2
| v2 -> v1
| _ -> ""
但是,我收到了警告:
warning FS0026: This rule will never be matched
warning FS0026: This rule will never be matched
它没有按预期工作:
> oppose "a" "a" "b"
val it : string = "b"
> oppose "b" "a" "b"
val it : string = "b"
我希望在第二次通话中得到“a”。我做错了什么?
答案 0 :(得分:3)
match子句中使用的名称是分配给结果的名称,而不是对值的检查。您需要明确检查:
let oppose v v1 v2 =
match v with
| a when a = v1 -> v2
| b when b = v2 -> v1
| _ -> ""
您也可以使用if
代替匹配。如果您正在检查值,则可以更简单地阅读,如下例所示:
let oppose v v1 v2 =
if v = v1 then v2
elif v = v2 then v1
else ""