我写了这个笨重的功能,虽然有效但不是最佳的。使用memoization编写递归函数以计算F#中的阶乘的有效方法是什么?该函数可以返回带有结果的字典类型数据结构,或者将它们存储在像此函数这样的变量中。
open System.Collections.Generic
let factorials = Dictionary<int, int>()
factorials.Add(1, 1)
let rec factorial n =
if n <= 1 then 1
else
match factorials.TryGetValue(n) with
| true, _ -> n * factorial(n-1)
| false, _ ->
factorials.Add(n, n * factorial(n-1))
n * factorial(n-1)
let a = factorial 9
答案 0 :(得分:1)
open System.Collections.Generic
let factorials = Dictionary<int, int>()
factorials.Add(1,1)
let factorial n =
let dictValue : int ref = ref 0
let rec factorialWithAcc n limit acc =
match n with
| x when n > limit -> ()
| _ ->
let acc = acc * n
if factorials.TryGetValue(n,dictValue)
then ()
else factorials.Add(n,acc)
factorialWithAcc (n+1) limit acc
factorialWithAcc 1 n 1
let printFact () =
let rec printFact n =
match n with
| 0 -> ()
| _ ->
printfn "n: %A, %A" n factorials.[n]
printFact (n-1)
printFact factorials.Count
let test () =
let result = factorial 9
printFact ()
test ()