【问题标题】:Recursive Factorial Function in F# with MemoizationF# 中带有记忆的递归阶乘函数
【发布时间】:2013-12-12 09:22:05
【问题描述】:

我只是在学习 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

我的问题是:

  1. 为什么我需要在错误匹配结束时调用n * factorial (n-1)?
  2. 为什么在真正的匹配中-&gt; 之后需要一个表达式?

【问题讨论】:

  • 这是阶乘函数的简单记忆版本。

标签: recursion f#


【解决方案1】:

解决 cmets:

真正匹配的更常见版本是

|true,result -> result 

您需要-&gt; 后面的位来实际返回一个值。

在错误匹配中,您需要通过计算来实际计算阶乘

n * factorial(n-1)

事实上,错误案例的更好版本应该是

 |false, _ -> 
     let r = n * factorial(n-1)
     factorials.Add(n,r)
     r

【讨论】:

  • TryGetValue 返回一个布尔值(显然只有一个值),那么真假之后的第二个元素是什么(导致你的答案)?另外,为什么我不能在错误匹配中的“->”之后只使用“factorials.Add(n, n * factorial(n-1))”?
  • Trygetvalue 实际上也返回一个值 - 请参阅此处 msdn.microsoft.com/en-us/library/bb347013(v=vs.110).aspx 。这就是您的版本需要_ 的原因。你可以有你的版本,但是递归调用两次很浪费。
  • TryGetValue 有一个 out 参数,F# 将其作为第二个元素。
【解决方案2】:
// Access the library containing the Dictionary module
open System.Collections.Generic

// Crate a key value,pair named factorials, e.g. table, to hold the
// the factorial number n and it's result.
let factorials = Dictionary<int, int>()

// Add an initial entry into the factorials table for the 
// value for one and the result of the factorial of one, being one.
factorials.Add(1, 1)

// Define a recursive function for factorial
// taking one integer parameter
let rec factorial n =
    // If the parameter is less than or equal to one
    // then return one
    if n <= 1 then 1
    // If the parameter is greater than one then
    else
        // look up the result of the factorial in the factorials table.
        // Use TryGetValue when looking up value to avoid errors when
        // there is no matching key for the value.
        // There is a problem here with the way TryGetValue is used.
        // It should be used as
        //   let mutable factresult
        //   factorials.TryGetValue(n,factresult)
        // The problem causes the result of TryGetValue(n) to be
        // the tuple (bool * int) instead of bool with the 
        // value part updating the mutable factresult.
        // Next the patterns for the match are true,_ and false, _ 
        // which match the tuple of the TryGetValue(n)
        // but the _ means to toss out the value it matches
        // because it doesn't have a name, 
        // so the whole use of the factorials table is not needed.
        match factorials.TryGetValue(n) with
        // If there is an entry in the factorials table then take this action.
        // Take n and multiply it by the factorial of n-1.
        // As an example for 5 this becomes 5 * 4 * 3 * 2 * 1
        // Take the result of n * factorial(n-1) and push it on to the stack
        // as the result of the function. 
        | true, _  -> n * factorial(n-1)
        // If there is no entry in the factorials table then
        // calculate the result of the factorial of n, i.e. n * factorial(n-1))
        // and add it to the factorials table.
        // Take the result of n * factorial(n-1) and push it on to the stack
        // as the result of the function. 
        | false, _ -> 
            factorials.Add(n, n * factorial(n-1))
            n * factorial(n-1)     

let a = factorial 9

更好的solution。

编辑

1.为什么我需要在错误匹配结束时调用n * factorial(n-1)?

我认为您来自命令式背景,并且很可能是 C#,因为您使用了 Dictionary。函数式代码不是命令式代码。当用函数式语言编码时,必须考虑函数。函数通过将其结果放入堆栈来结束,并且对于除异常之外的所有退出函数的方式都必须以相同的类型签名结束

所以对于这个匹配函数

   match factorials.TryGetValue(n) with
    | true, _  -> n * factorial(n-1)
    | false, _ -> 
        factorials.Add(n, n * factorial(n-1))
        n * factorial(n-1)

函数有两种结束方式。一个通过真,一个通过假。因此,这两个分支都以每个分支中最后一个函数的 int 退出。

即

n * factorial(n-1)

2.为什么在真匹配中->后面需要一个表达式?

匹配语句获取匹配结果,例如factorials.TryGetValue(n) 并匹配可能的模式。由于此匹配的签名是 (bool * int),因此您已将所有模式与 (true,) 和 (false,) 匹配。现在,对于每个匹配模式,您必须拥有详细说明要做什么的代码。 -> 将模式与详细说明要做什么的代码分开。将匹配和模式视为 switch 语句。您需要对每个开关选项进行一些操作。

【讨论】:

  • 感谢您的详细解释。您链接到的答案不包括记忆,但这是本练习的重点。附:我来自 C# 领域,这就是我尝试学习 F# 和函数式编程的原因,感谢您的建议
  • 你在问题​​或标题中提到记忆的地方是什么?
  • 你如何写一个带有记忆的阶乘函数?该函数不必返回最大输入的值,更好的是返回字典(或类似的数据结构)与输入的阶乘?
猜你喜欢
  • 2012-04-01
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多