【发布时间】:2013-01-28 11:46:05
【问题描述】:
F# 的模式匹配非常强大,写起来感觉很自然:
match (tuple1, tuple2) with
| ((a, a), (a, a)) -> "all values are the same"
| ((a, b), (a, b)) -> "tuples are the same"
| ((a, b), (a, c)) -> "first values are the same"
// etc
但是,第一个模式匹配会导致编译器错误:
'a' is bound twice in this pattern
有没有比以下更清洁的方法?
match (tuple1, tuple2) with
| ((a, b), (c, d)) when a = b && b = c && c = d -> "all values are the same"
| ((a, b), (c, d)) when a = c && b = d -> "tuples are the same"
| ((a, b), (c, d)) when a = c -> "first values are the same"
// etc
【问题讨论】:
-
对于任何感兴趣的人:“F# 的模式匹配非常强大”。 F# 继承的模式匹配的 ML 风格实际上故意不那么强大。具体来说,ML 将模式限制为所谓的线性模式,以保证匹配模式所花费的时间量受模式大小的限制。在 F# 中,活动模式规避了这一点,让您可以在模式匹配的过程中做任何事情。缺点是性能难以预测。 Mathematica 将这一点发挥到了极致。
标签: f# pattern-matching