如何在F#中比较x和y? [英] How do I compare x and y in F#?
问题描述
我需要有关将2个数字进行比较的匹配模式的帮助.像这样的东西:
I need help with the matching pattern that would compare 2 numbers. Something like that:
let test x y =
match x with
| y when x < y -> printfn "less than"
| y when x > y -> printfn "greater than"
| _ -> printfn "equal"
当x为0且y为200时,它以某种方式落入"_"情况.我在这里做错什么了?
Somehow it falls to the "_" case when x is 0 and y is 200. What am I doing wrong here?
推荐答案
您的代码存在的问题是您编写时:
The problem with your code is that when you write:
match x with
| y when x < y -> (...)
..这意味着您要将x
的值(match <expr> with
中的<expr>
)分配给名为y
的新变量(| <pat> when ...
中的<pat>
),然后进行比较值为x
的新y
(现在包含x
的值)-因此它将始终返回false
.您始终可以重命名绑定变量,因此您的代码与编写相同:
.. it means that you want to assign the value of x
(the <expr>
in match <expr> with
) to a new variable named y
(the <pat>
in | <pat> when ...
) and then compare this new y
(which now contains the value of x
) with the value of x
- and so this will always return false
. You can always rename the bound variable, so your code is the same as writing:
match x with
| newY when x < newY -> (...)
现在您可以看到为什么它永远不匹配-因为您只是将x
与自身进行比较!
Now you can see why this never matches - because you are just comparing x
with itself!
如果您具有一些更复杂的结构的输入(例如元组或有区别的联合,列表,数组,选项类型等),则模式匹配特别有用.但是,如果您只想比较数字,则使用
Pattern matching is especially useful if you have inputs of some more complicated structure - like tuples or discriminated unions, lists, arrays, option types etc. But if you simply want to compare numbers, it is much easier to just use if
:
let test x y =
if x < y then printfn "less than"
elif x > y then printfn "greater than"
else printfn "equal"
在您的match
中,您实际上并不需要绑定任何变量-但是John的解决方案演示了如何实现该工作-它只是说,接受变量x
和y
并将它们分配给new变量x
和y
(它们具有相同的名称).
In your match
, you do not really need to bind any variables - but the solution by John demonstrates how you can make that work - it simply says, take variables x
and y
and assign them to new variables x
and y
(which just have the same name).
这篇关于如何在F#中比较x和y?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!