Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In F#, return true if expression matches pattern?

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?

like image 601
SoftMemes Avatar asked Mar 09 '14 16:03

SoftMemes


People also ask

What is 1 C equal to in Fahrenheit?

Answer: 1° Celsius is equivalent to 33.8° Fahrenheit.

What is the difference between 1 degree Celsius and 1 degree 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).

What temperature in Fahrenheit is 50 C?

Answer: 50° Celsius is equal to 122° Fahrenheit.


2 Answers

You could shorten it slightly using function:

let f = function ['A'::_] -> true | _ -> false
like image 124
Lee Avatar answered Oct 17 '22 08:10

Lee


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.

like image 32
Søren Debois Avatar answered Oct 17 '22 09:10

Søren Debois