我正在尝试打破下面的这种循环依赖,但不确定最好的方法。
let cashOpeningBalance t =
if t = 1 then
0.0
else
cashClosingBalance (t - 1)
let cashInterest t =
cashOpeningBalance t * 0.03
let accumulatedCash t =
cashOpeningBalance t + cashInterest t
// let moreComplicatedLogic t = ...
let cashClosingBalance t =
accumulatedCash t
使用这个答案中的一些逻辑,我想出了以下解决方案,但性能真的很差。
let cashOpeningBalance t cashClosingBalance =
if t = 1 then
10.0
else
cashClosingBalance (t - 1)
let cashInterest t cashClosingBalance =
(cashOpeningBalance t cashClosingBalance) * 0.03
let accumulatedCash t cashClosingBalance =
(cashOpeningBalance t cashClosingBalance) + (cashInterest t cashClosingBalance)
// let moreComplicatedLogic t cashClosingBalance = ...
let rec cashClosingBalance t =
//accumulatedCash t cashClosingBalance
let temp = accumulatedCash t cashClosingBalance
printfn "Cash Closing Balance = %f Where t = %i" temp t
temp
cashClosingBalance 3
(*
>
Cash Closing Balance = 10.300000 Where t = 1
Cash Closing Balance = 10.300000 Where t = 1
Cash Closing Balance = 10.609000 Where t = 2
Cash Closing Balance = 10.300000 Where t = 1
Cash Closing Balance = 10.300000 Where t = 1
Cash Closing Balance = 10.609000 Where t = 2
Cash Closing Balance = 10.927270 Where t = 3
val it : float = 10.92727
*)
cashClosingBalance 50
(*
Takes a really long time
*)
无论如何要重写 cashClosingBalance 函数来停止过多的递归调用,如下面的输出所示?我真的需要能够输入高达 400 的 t 值,并且它仍然可以在几秒钟内运行。