gpt4 book ai didi

f# - 如何在 F# 中对 HttpMethod 进行模式匹配?

转载 作者:行者123 更新时间:2023-12-01 09:54:57 26 4
gpt4 key购买 nike

request 是来自 System.Net.HttpHttpRequestMessage,我正在尝试使用模式匹配来确定使用了哪种方法提出请求。

这是一个证明我的问题的人为例子:

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"
| _ -> ""

关于f# - 如何在 F# 中对 HttpMethod 进行模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com