f# - 检查几种选项类型,然后转换为类型

标签 f# pattern-matching discriminated-union option-type

总的来说,我是一名新程序员,对于 F# 也是如此。我已经多次遇到这个特定问题,但我认为尚未有效解决它。问题是这样的:

我有这些示例类型:

 type Retail1 = | Fashion | Auto | Sports
 type Wholesale1 = | Fashion | Auto | Sports
 type Events1 = | Wedding | Birthday 

 type Product = 
      | Retail of Retail1 | Wholesale of Wholesale1 | Events of Events1
      | NoProduct

我想通过函数将前三种类型的可能性转换为Product类型:

 let convertToProduct (retail: Retail1 option) 
      (wholesale: Wholesale1   option) (events: Events1 option) =
      // convert to Product here
      if retail.IsSome then Retail retail
      elif wholesale.IsSome then Wholsale wholseale
      elif events.IsSome then Events events
      else NoProduct

我在传递中处理它的方式只是将一个很长的 if elif 语句链接在一起来检查每个条件并返回 Product 的最终类型,但这感觉不正确,或者至少是惯用的F#。解决这个问题的推荐方法是什么?

最佳答案

像这样怎么样:

let convertToProduct (retail: Retail1 option) (wholesale: Wholesale1 option) (events: Events1 option) =
    match (retail, wholesale, events) with
    |Some rt, None, None -> Retail rt
    |None, Some wh, None -> Wholesale wh
    |None, None, Some ev -> Events ev
    |_ -> NoProduct

这利用了这样一个事实:如果将所有参数转换为元组,则可以对结果进行非常简洁的模式匹配。

模式匹配实际上非常强大,您可以在 MSDN documentation 中找到有关可以执行的模式匹配类型的更多详细信息。 .

关于f# - 检查几种选项类型,然后转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37579746/

相关文章:

f# - Azure 和 F# 3.0 类型提供程序

recursion - 递归可区分联合和映射

sockets - Erlang 变量模式匹配

algorithm - 短语模板检测

生成的受歧视联合上出现 typescript 错误

.net - F#中的元编程示例

wpf - 将 WPF 的控件绑定(bind)到 F# 选项

pattern-matching - sml 中的逻辑简化

functional-programming - 表示所有扩展 "base"记录的记录总和类型概念的规范方法

typescript - 即使在使用类型保护检查之后也无法缩小对象属性的类型