如何在 F# 中对 HttpMethod 进行模式匹配?
How can I pattern match on a HttpMethod in F#?
其中 request
是来自 System.Net.Http
的 HttpRequestMessage
,我正在尝试使用模式匹配来确定使用哪种方法发出请求。
这是一个证明我的问题的人为示例:
let m = match request.Method with
| HttpMethod.Get -> "GET"
| HttpMethod.Post -> "POST"
这导致:
Parser error: The field, constructor or member 'Get' is not defined
为什么这不起作用,我如何使用模式匹配或更合适的技术来实现相同的目标?
正如 John Palmer 在他的评论中指出的那样,您可以这样写:
let m =
match request.Method with
| x when x = HttpMethod.Get -> "GET"
| x when x = HttpMethod.Post -> "POST"
| _ -> ""
但是,如果您要重复执行此操作,您可能会觉得这有点麻烦,在这种情况下,您可以为其定义一些 Active Patterns:
let (|GET|_|) x =
if x = HttpMethod.Get
then Some x
else None
let (|POST|_|) x =
if x = HttpMethod.Post
then Some x
else None
你可以这样写:
let m =
match request.Method with
| GET _ -> "GET"
| POST _ -> "POST"
| _ -> ""
另一种使用 Active Patterns 的方法最终得到的代码比 Mark 的解决方案中的代码稍微好一点,它是一个像这样的模式函数(使用完整的分类模式):
let (|GET|POST|PUT|DELETE|OTHER|) x =
if x = HttpMethod.Get
then GET
elif x = HttpMethod.Post
then POST
elif x = HttpMethod.Put
then PUT
elif x = HttpMethod.Delete
then DELETE
else OTHER
这种方法可以让你去掉模式匹配中的下划线:
let m =
match request.Method with
| GET -> "GET"
| POST -> "POST"
| _ -> ""
其中 request
是来自 System.Net.Http
的 HttpRequestMessage
,我正在尝试使用模式匹配来确定使用哪种方法发出请求。
这是一个证明我的问题的人为示例:
let m = match request.Method with
| HttpMethod.Get -> "GET"
| HttpMethod.Post -> "POST"
这导致:
Parser error: The field, constructor or member 'Get' is not defined
为什么这不起作用,我如何使用模式匹配或更合适的技术来实现相同的目标?
正如 John Palmer 在他的评论中指出的那样,您可以这样写:
let m =
match request.Method with
| x when x = HttpMethod.Get -> "GET"
| x when x = HttpMethod.Post -> "POST"
| _ -> ""
但是,如果您要重复执行此操作,您可能会觉得这有点麻烦,在这种情况下,您可以为其定义一些 Active Patterns:
let (|GET|_|) x =
if x = HttpMethod.Get
then Some x
else None
let (|POST|_|) x =
if x = HttpMethod.Post
then Some x
else None
你可以这样写:
let m =
match request.Method with
| GET _ -> "GET"
| POST _ -> "POST"
| _ -> ""
另一种使用 Active Patterns 的方法最终得到的代码比 Mark 的解决方案中的代码稍微好一点,它是一个像这样的模式函数(使用完整的分类模式):
let (|GET|POST|PUT|DELETE|OTHER|) x =
if x = HttpMethod.Get
then GET
elif x = HttpMethod.Post
then POST
elif x = HttpMethod.Put
then PUT
elif x = HttpMethod.Delete
then DELETE
else OTHER
这种方法可以让你去掉模式匹配中的下划线:
let m =
match request.Method with
| GET -> "GET"
| POST -> "POST"
| _ -> ""