Where request
is a HttpRequestMessage
from System.Net.Http
, I'm trying to use pattern matching to determine which method was used to make the request.
This is a contrived example which demonstrates my problem:
let m = match request.Method with
| HttpMethod.Get -> "GET"
| HttpMethod.Post -> "POST"
which results in:
Parser error: The field, constructor or member 'Get' is not defined
Why doesn't this work, and how can I use pattern matching or a more appropriate technique to achieve the same goal?
As John Palmer points out in his comment, you could write it like this:
let m =
match request.Method with
| x when x = HttpMethod.Get -> "GET"
| x when x = HttpMethod.Post -> "POST"
| _ -> ""
However, if you're going to be doing this repeatedly, you may find this a bit cumbersome, in which case you could define some Active Patterns for it:
let (|GET|_|) x =
if x = HttpMethod.Get
then Some x
else None
let (|POST|_|) x =
if x = HttpMethod.Post
then Some x
else None
Which would enable you to write this:
let m =
match request.Method with
| GET _ -> "GET"
| POST _ -> "POST"
| _ -> ""