How can I match pattern to HttpMethod in F #?

Where request

is 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 to demonstrate my problem:

let m = match request.Method with
      | HttpMethod.Get -> "GET"
      | HttpMethod.Post -> "POST"

      

that leads to:

Parser error : 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?

+3


source to share


1 answer


As John Palmer points out in his comment, you can 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 are going to do this multiple times, you may find it a little cumbersome, in which case you can define Active templates 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

      

So that you could write this:

let m =
    match request.Method with
    | GET _ -> "GET"
    | POST _ -> "POST"
    | _ -> ""

      

+6


source







All Articles