根据Brian的回答,模式匹配与switch语句不同。它们测试和分解输入的结构,而不是测试对象的相等性。但是,如果在整个程序中经常使用将颜色划分为黑色、白色和其他颜色,则活动模式可能是一个选项。对于一次性的“锅炉板”成本,它们允许您围绕正在操作的对象定义结构。例如,
open System.Drawing
let (|Black|White|Other|) (color:Color) =
if color = Color.Black then Black
elif color = Color.White then White
else Other
let testColor c =
match c with
| Black -> 1
| White -> 0
| Other -> failwith "unexpected color"
或者,如果您同样只处理黑色和白色,但始终希望黑色的值为1,白色的值为0,则可以使用部分活动模式:
let (|KnownColor|_|) (color:Color) =
if color = Color.Black then Some(1)
elif color = Color.White then Some(0)
else None
let testColor2 c =
match c with
| KnownColor i -> i
| _ -> failwith "unexpected color"
更一般地,您甚至可以使用通用的部分活动模式模拟switch语句:
let (|Equals|_|) (lhs) (rhs) =
if lhs = rhs then Some(lhs) else None
let testColor3 c =
match c with
| Equals Color.Black _ -> 1
| Equals Color.White _ -> 0
| _ -> failwith "unexpected color"
let testString c =
match c with
| Equals "Hi" _ -> 1
| Equals "Bye" _ -> 0
| _ -> failwith "unexpected string"