Reputation: 1397
Now I understand that the first line of code can be shortened to the second one. This is the first time I'm running into it and I can't find any documentation on what the operator is called. Is it an abstract concept that can be used for other things as well?
let contains optValue value =
Option.exists (fun v -> v >= value) optValue
let contains optValue value =
Option.exists ((>=) value) optValue
Upvotes: 3
Views: 95
Reputation: 36738
You've already been told that the second example should have been (=)
for your two functions to be equivalent, so I won't go over that. But I want to warn you that using the >=
operator in this way might work differently than what you expect. The underlying reason has to do with how F# does partial application, and https://fsharpforfunandprofit.com/series/thinking-functionally.html is the best reference for that. (The relevant parts are the articles on currying and partial application, but you'll want to read the whole thing in order since later articles build on concepts explained in earlier articles).
Now, if you've read those articles, you know that F# allows partial application of functions: if you have a two-parameter function f a b
, but you call it with just one parameter f a
, the result is a function that is expecting a parameter b
, and when it receives that, it executes f a b
. When you wrap an operator in parentheses, F# treats it like a function, so when you do (>=) value
, you get a function that's awaiting a second parameter x
, and will then evaluate (>=) value x
. And when F# evaluates (op) a b
, whatever the operator is, it's the same as a op b
, so (>=) value x
is the same as value >= x
.
And that's the bit that trips most people up at first. Because when you read Option.exists ((>=) value) optValue
, you naturally want to read that as "Does the option contain something greater than or equal to value
"? But in fact, it's actually saying "Does the option contain a value x
such that value >= x
is true?", i.e., something less than or equal to value
.
So the simple rules of partial application, applied consistently, can lead to unexpected results with greater-than or less-than operators, or in fact any operator that isn't commutative. Be aware of this, and if you want to use partial application with non-commutative operators, double-check your logic.
Upvotes: 5