I am looking for a shorter/neater way of doing the equivalent of the following (for any pattern known at compile time):
let f x = match x with | ['A'::_] -> true ; | _ -> false
is there a way of doing this in general, i.e. return true iff an expression matches a given pattern?
Answer: 1° Celsius is equivalent to 33.8° Fahrenheit.
In the Celsius scale there are 100 degrees between the freezing point and the boiling point of water compared to 180 degrees in the Fahrenheit scale. This means that 1 °C = 1.8 °F (check the section about temperature differences below).
Answer: 50° Celsius is equal to 122° Fahrenheit.
You could shorten it slightly using function
:
let f = function ['A'::_] -> true | _ -> false
In f#, patterns are not values themselves, and there is no mechanism for converting them to values(*). So, no, there is no neater way.
That said, you may have other options depending on why you're interested in checking whether a pattern matches. Caring about whether a pattern matches but not about which values were matched seems a bit unusual to me, so maybe there's an opportunity for refactoring.
As a simple example, suppose you're doing this:
let t = match e with <pattern> -> true | _ -> false
...
if t then
(* Do something. *)
else
(* Do something else. *)
...
In that case, you could consider instead doing this:
...
match e with
<pattern> -> (* Do something. *)
| _ -> (* Do something else. *)
...
(Supposing the test happens only once, of course.)
(*) Ignoring reflection and quotations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With