【发布时间】:2016-09-01 03:02:55
【问题描述】:
我尝试用谷歌搜索这个,但我找不到引导我去做我想做的事情的词集。
我正在尝试解决Project Euler Problem 54,我有这个相当荒谬的功能:
let evaluate hand =
if isRoyalFlush hand then 9
elif isStraightFlush hand then 8
elif isFour hand then 7
elif isFullHouse hand then 6
elif isFlush hand then 5
elif isStraight hand then 4
elif isThree hand then 3
elif isTwoPair hand then 2
elif isPair hand then 1
else 0
所有isSomething 关键字都是接受string array 并返回布尔值的函数。有没有更优雅的方式使用模式匹配来做到这一点?
这不起作用:
match true with
| isRoyalFlush hand -> 9
| isStraightFlush hand -> 8
// .. etc
我正在寻找这样的东西:
match hand with
| isRoyalFlush -> 9
| isStraightFlush -> 8
// .. etc
我记得有一次看到过类似的东西,但我不记得在哪里或如何找到它。
【问题讨论】:
-
主动模式就是你想要的
-
主动模式方法看起来稍微好一些,但它上面需要很多样板。我更喜欢@FuleSnabel 的答案,它只使用高阶函数和数据。但实际上,我认为你的代码很好,而且完全可以理解。添加一些列对齐可能会降低它在未来被意外破坏的可能性。
-
我也认为OP发布的代码没有什么特别的问题。
标签: f# pattern-matching active-pattern