【发布时间】:2019-11-19 13:07:33
【问题描述】:
我正在编写一个匹配项,我在函数 f 上使用“when”表达式限制匹配项。我想绑定 f 的结果以用于以下表达式。我希望我的代码看起来像这样:
match input with
| input when f x input -> //Some exp where (f x input) is used but not recomputed
| input when f y input -> //Some exp where (f x input) is used but not recomputed
显而易见的解决方案是简单地重新计算结果,但我想知道是否可以使用其他机制。
【问题讨论】:
-
你不需要重新计算结果:如果模式匹配,你知道
f x input = true -
在这个例子中,
f必须是一个布尔值,when f x input才能正确编译。如果你想让f成为一个返回任意类型的函数,你需要active patterns。特别注意Int和Bool示例:如果活动模式的结果是Some x,则将其匹配为Int y会将值x分配给y。如果这还没有意义,请阅读文章并进行一些实验。 -
或者只使用
if表达式。仅仅因为你有一把花哨的锤子并不意味着一切都必须是钉子。
标签: f# pattern-matching