如何比较F#中的x和y?

如何比较F#中的x和y?,f#,pattern-matching,F#,Pattern Matching,我需要有关比较两个数字的匹配模式的帮助。诸如此类: let test x y = match x with | y when x < y -> printfn "less than" | y when x > y -> printfn "greater than" | _ -> printfn "equal" 让测试x y= 将x与 |当xprintfn“小于”时为y |当x>y->printfn“大于”时为y |->printfn“相等”

我需要有关比较两个数字的匹配模式的帮助。诸如此类:

let test x y =
   match x with
   | y when x < y -> printfn "less than"
   | y when x > y -> printfn "greater than"
   | _ -> printfn "equal"
让测试x y=
将x与
|当xprintfn“小于”时为y
|当x>y->printfn“大于”时为y
|->printfn“相等”

不知何故,当x为0,y为200时,它就落在了“u”的情况下。我在这里做错了什么?

代码的问题是,当您编写时:

match x with 
| y when x < y -> (...)
现在,您可以了解为什么这永远不匹配-因为您只是在将
x
与自身进行比较

如果您有一些更复杂结构的输入,例如元组或区分的并集、列表、数组、选项类型等,则模式匹配尤其有用。但如果您只是想比较数字,只需使用
if

let test x y =
  if x < y then printfn "less than"
  elif x > y then printfn "greater than"
  else printfn "equal"
让测试x y=
如果xy,则打印fn“大于”
else printfn“相等”

match
中,您实际上不需要绑定任何变量-但John的解决方案演示了如何实现这一点-它简单地说,将变量
x
y
分配给新变量
x
y
(它们只有相同的名称).

更好的版本是在两个数字上进行模式匹配,就像这样

let test x y =
   match (x,y) with
   | (x,y) when x < y -> printfn "less than"
   | (x,y) when x > y -> printfn "greater than"
   | _ -> printfn "equal"
让测试x y=
将(x,y)与
|(x,y)当xprintfn“小于”时
|(x,y)当x>y->printfn“大于”时
|->printfn“相等”
如果您咨询您使用的模式匹配类型,那么它将是所谓的变量模式,其中匹配案例中的新变量
y
将被分配匹配表达式
x
的值。由于
y
变量在
match
语句中隐藏了原始函数参数
y
,因此在第一种和第二种情况下
y
将仅获取
x
的值,因此当
保护都失败时
。然后,第三个catch all match case
\uuu
开始,这样您就得到了“相等”的回报,正如所观察到的那样

如果浏览以下代码段,您可以更好地看到发生了什么:

let f x y =
    match x with
    | y -> y
并尝试使用类似于
f arg1 arg2
f
将始终返回
arg1
,无论
arg2
值如何

您可以通过将参数比较移动到
match
表达式中来表达您的原始意图,仍然使用与常量模式匹配:

let test x y =
    match sign (Operators.compare x y) with
    | 1 -> "greater than"
    | -1 -> "less then"
    | _ -> "equal"
将匹配x替换为匹配y

让测试x y=
匹配
|当xprintfn“小于”时为y
|当x>y->printfn“大于”时为y
|->printfn“相等”

模式匹配是一个糟糕的选择,如果
,请使用

if x < y then
  printfn "less than"
elif x > y then
  printfn "greater than"
else
  printf "equal"
如果xy那么
printfn“大于”
其他的
printf“相等”

与约翰·帕默的答案类似。我认为这样写会提高你对正在发生的事情的理解:

let test x y = 
    match (x,y) with
    | (a,b) when a < b -> printfn "less than"
    | (a,b) when a > b -> printfn "greater than"
    | _ -> printfn "equal"
让测试x y=
将(x,y)与
|(a,b)当aprintfn“小于”时
|(a,b)当a>b->printfn“大于”时
|->printfn“相等”

简单来说,当您使用
Match
语句时,模式中的术语(即
->
前面的部分)声明新标识符。当您在模式中重复使用
y
时,您将隐藏以前的标识符
y
,并创建一个新的标识符,该标识符与您要匹配的对象具有相同的值,在本例中为标识符
x
。换句话说,您总是将
x
的值与自身进行比较。正如其他人所指出的,最好使用
if
语句。

有趣的方法基因。
if x < y then
  printfn "less than"
elif x > y then
  printfn "greater than"
else
  printf "equal"
let test x y = 
    match (x,y) with
    | (a,b) when a < b -> printfn "less than"
    | (a,b) when a > b -> printfn "greater than"
    | _ -> printfn "equal"