gpt4 book ai didi

F#:嵌套的可区分联合和匹配

转载 作者:行者123 更新时间:2023-12-02 20:52:20 25 4
gpt4 key购买 nike

我有 2 个嵌套的受歧视联合:

type ServiceTypes =
| Contexts
| Context of int
| Producers

type ServiceActions =
| Get of ServiceTypes
| Update of ServiceTypes

还有一个嵌套的匹配语句:

let s_action = match action with
| Get(stype) -> sprintf "Get%s" (match stype with
| Contexts -> sprintf "Contexts"
| Context(id) -> (sprintf "Context/%d" id))
| _ -> raise (RequestException("get"))
| Update(stype) -> sprintf "Update%s" (match stype with
| Producers -> (sprintf "Producers")
| _ -> raise (RequestException("update")))

目标是使用类似于 req.Send(Update Producers) 的调用构建请求字符串。

无论如何,由于我不明白的原因,编译器给了我两个警告:

  1. Update(stype)上,我得到一个此规则将永远不会匹配
  2. 在第一个匹配类型上,我在此表达式上得到了不完整的模式匹配。例如,值“Producers”可能表示模式未涵盖的情况。

所以问题是为什么我会收到这两个警告?我是否错过了匹配工作方式中的某些内容?

最佳答案

虽然嵌套匹配表达式有时是有必要的,但在这种特殊情况下,如果我是你,我会编写一个更具可读性的单级匹配:

let s_action = 
match action with
| Get Contexts -> "GetContexts"
| Get (Context id) -> sprintf "GetContext/%d" id
| Update Producers -> "UpdateProducers"
| Get _ -> raise (RequestException "get")
| Update _ -> raise (RequestException "update")

它达到了与您的代码完全相同的效果。

关于F#:嵌套的可区分联合和匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9136525/

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