f# - 在 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"
一个实际的例子是:
- "a" 做了一些操作
- "b" 重置一个计数器,然后执行与 "a" 相同的操作
并且您希望避免代码重复,还要将代码放在外部函数中。
解决方案
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
推荐阅读
- tensorflow2.0 - tf.compat.v1.disable_eager_execution() 和 tf.data.dateset
- kotlin - 如何在 CoroutineExceptionHandler 中捕获特定异常
- python - 如何使用 Pandas to_html 将相同的 html bg 颜色应用于所有列
- java - 如何在 Spring MVC 中将用户输入与 BigDecimal 对象字段绑定?
- python - 如何在没有交叉函数的情况下从 joblib 运行具有多参数的并行函数
- cordova - ionic 5 和 cordova - 构建错误:为 iOS 构建时 xcworkspace 不是工作区文件
- amazon-web-services - 如何从 EMR 集群的 AWS Paramstore 中提取参数
- python - 在 Mac 上运行 python 应用程序而不安装 python
- here-api - Bug: POI图片heremap api api code和apikey的区别
- node.js - 模拟 fs readFile 在原始值上给出了 Cannot spyOn ;给定的未定义