有没有办法简化这条线?

时间:2012-09-20 22:29:52

标签: f#

if reelID = reelWeights.Count - 1
    then Array.fold calc1 (0L,0) reelWeights.[reelID]
    else Array.fold calc2 (0L,0) reelWeights.[reelID]

我尝试使用管道,似乎放慢了一点(不确定原因):

reelWeights.[reelID]
    |> (if reelID = reelWeights.Count - 1 then Array.fold calc1 else Array.fold calc2) (0L,0)

如果我这样做

let calc x = if x then calc1 else calc2
Array.fold (calc reelID = reelWeights.Count - 1) (0L,0) reelWeights.[reelID]

然后在循环中冗余检查条件的成本看起来很不错。

2 个答案:

答案 0 :(得分:5)

假设calc1calc2具有相同的签名(或者如果它们是值而不是函数,则属于同一类型):

let calc = if reelID = reelWeights.Count - 1 then calc1 else calc2
Array.fold calc (0L, 0) reelWeights.[reelID]

答案 1 :(得分:1)

或者在一行中:

let weight = 
    Array.fold (if reelID = (reelWeights.Count - 1) then calc1 else calc2) (0L,0) reelWeights.[reelID]