如果你两个数字范围之间就像在你的榜样选择,我会 只用一个if-then-else
表达:
let realTick population =
let fitness = getFullFitness population
if 0 <= fitness && fitness <= 50 then
population
else
childGeneration population
或简单后卫:
let realTick population =
match getFullFitness population with
| fitness when 0 <= fitness && fitness <= 50 ->
population
| _ ->
childGeneration population
如果你的实际选择要复杂得多,那么你可能需要使用 活动模式。不像@pad,我会用一个参数活跃模式:
let (|BetweenInclusive|_|) lo hi x =
if lo <= x && x <= hi then Some() else None
let realTick population =
match getFullFitness population with
| BetweenInclusive 0 50 ->
population
| _ ->
childGeneration population
一个我发现有时候是有用的高阶主动模式是一般 目的谓:
let (|Is|_|) predicate x =
if predicate x then Some() else None
使用Is
你可以写是这样的:
let lessEq lo x = x <= lo
let greaterEq hi x = hi <= x
let realTick population =
match getFullFitness population with
| Is (greaterEq 0) & Is (lessEq 50) ->
population
| _ ->
childGeneration population
需要注意的是,虽然这样的事情是矫枉过正在这样一个简单的例子, 它可以在更复杂的情况下方便。我个人使用与此类似的活动 模式在优化 编译器中实现简化通过,该编译器在大量基本操作的例子和为这些基元提供的参数的属性上进行模式匹配。