首页 > 解决方案 > 将嵌套匹配表达式转换为函数

问题描述

我有一些嵌套的歧视联合

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

这是一个接受 aDog并返回 a的函数string

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

我可以将第一个转换matchfunction语法:

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

如何将第二个转换matchfunction

标签: f#pattern-matching

解决方案


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

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

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


推荐阅读