【问题标题】:Convert nested match expression to function将嵌套匹配表达式转换为函数
【发布时间】:2020-03-06 02:39:29
【问题描述】:

我有一些嵌套的可区分联合

type Job = Sniff | Guard
type Dog = Chihuahua | GermanShepherd of Job

这是一个接受Dog 并返回string 的函数。

let dogPrinter d =
    match d with
    | Chihuahua -> ""
    | GermanShepherd g ->
        match g with
        | Sniff -> ""
        | Guard -> ""

我可以将第一个match 转换为function 语法:

let dogPrinter = function
    | Chihuahua -> ""
    | GermanShepherd g ->
        match g with
        | Sniff -> ""
        | Guard -> ""

如何将第二个match 转换为function

【问题讨论】:

  • 这似乎是XY problem为什么你想这样做?它是完全可读的。不过,您可以使用嵌套模式来避免第二次匹配。
  • 为什么?只是想知道如何。嵌套模式是什么意思?你能发布答案吗?

标签: f# pattern-matching


【解决方案1】:

在这种情况下避免嵌套匹配的惯用方法是使用嵌套模式:

let dogPrinter = function
    | Chihuahua -> ""
    | GermanShepherd Sniff -> ""
    | GermanShepherd Guard -> ""

您可以根据需要尽可能多地嵌套模式,就像在创建值时可以嵌套表达式一样。

【讨论】:

    【解决方案2】:

    我能想到的唯一方法,我认为这通常可能是最好的方法,因为它适当地分离了关注点。但是,我认为这个 function 关键字不会增加任何价值。我通常只使用match 关键字。

    let jobPrinter = function
      | Sniff -> ""
      | Guard -> ""
    
    let dogPrinter = function
      | Chihuahua -> ""
      | GermanShepherd job -> job |> jobPrinter
    

    【讨论】:

      【解决方案3】:

      虽然我认为@glennsl 回答是您应该考虑做的事情,但这是对 OP 要求的回答:

      type Job = Sniff | Guard
      type Dog = Chihuahua | GermanShepherd of Job
      
      let dogPrinter = function
          | Chihuahua -> "Voff"
          | GermanShepherd g ->
            g |> (  function 
                    | Sniff -> "Sniff"
                    | Guard -> "Guard"
                  )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-30
        • 1970-01-01
        • 2013-03-04
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多