The problem with your code is that when you write:
match x with
| y when x < y -> (...)
.. 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 -> (...)
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"
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).