首页 > 解决方案 > 在 F# 中,匹配表达式能否“通过”另一个匹配?就像在 C# 或 C++ 中一样?

问题描述

在 C++ 中,您可以使用 switch / case 构造并省略 case 语句中的 break 以使执行落在下一个 case 中。

在 C# 中,这是通过 goto case 完成的。

这可以在 F# 中完成吗?

AC# 示例来说明:

switch (a)
case "a":
    ...
    break;
case "b":
    ...
    goto case "a"
case "c":
    ...

我会想象这样的事情:

match x with
| "a" -> ...
| "b" -> ...  + goto "a"

一个实际的例子是:

并且您希望避免代码重复,还要将代码放在外部函数中。

标签: f#switch-statement

解决方案


F# 是一种基于表达式的语言,因此它没有像goto. 但是,您仍然可以表达相同的逻辑。首先,您可以组合“案例”:

let test str =
   match str with
   | (null|"") -> printf "empty"
   | str -> printf "String: [%s]" str

当然,如果您只想重用某些案例逻辑的一部分,您可以将其提取到本地函数中:

let test str =
   let onEmpty() = printf "empty!!!"
   match str with
   | null ->
       onEmpty()
       printf "null!"
   | "" -> onEmpty()
   | str -> printf "String [%s]" str

推荐阅读