【问题标题】:What does function return when "function times zero" in functional programming?函数式编程中“函数时间为零”时函数返回什么?
【发布时间】:2015-05-19 05:00:32
【问题描述】:

我被这个 SML 作业困住了。我正在尝试创建一个复合函数(有趣的复合 n f)。它应该将函数 f 应用于自身 n 次,例如,化合物 3 f 将等于 f(f(f(x)))。除了 n 为零的情况外,我让它工作。我问过教授,但他不会直接告诉我答案。他试图给我一个提示“什么是函数乘以零?”我还是想不通。 stackoverflow可以解决吗?

谢谢。

我的代码:

fun compound n f =
    if n < 2 then
        if n = 0 then fn x => f x else fn x => f x
    else fn x => f(compound (n-1) f(x));

示例:

val fnc = fn x => x + 1; (* example function to be used *)
compound 5 fnc(10); (* will return 15 which is correct*)
compound 0 fnc(10); (* returns 11, should be 10 *)

答案:

fun compound n f =
    if n < 2 then
        if n = 0 then fn x => x else fn x => f x
    else fn x => f(compound (n-1) f(x));

【问题讨论】:

  • if n = 0 then fn x =&gt; f x else fn x =&gt; f x 似乎是一个错字;两个分支是一样的(都是fn x =&gt; f x)。
  • 我就这样离开了,所以 SML 不要向我抛出丑陋的错误。

标签: sml


【解决方案1】:

我不会给你最终的答案,因为我不喜欢让老师不高兴;)但是,我会尝试一个我相信你会发现很容易完成的推导。

让我们从一个非常简单的案例开始。让我们“重新实现”函数应用程序,即,让我们编写一个接受函数和参数的函数,并将第一个参数应用于第二个参数:

fun apply f a = f a

让我们使用一个增加整数的人为函数来进行测试:

- fun inc n = n + 1;
val inc = fn : int -> int

- inc 1;
val it = 2 : int

- apply inc 1;
val it = 2 : int

现在,让我们编写apply2,它接受一个函数和一个参数,并将 param 函数两次应用于参数:

fun apply2 f a = f (f a)

让我们用inc来测试它:

- apply2 inc 1;
val it = 3 : int

似乎工作正常。如您所料,我们现在将实现apply3apply4 等等。让我们一起看看其中的一些:

fun apply f a = f a
fun apply2 f a = f (f a)
fun apply3 f a = f (f (f a))
fun apply4 f a = f (f (f (f a)))

看起来我们可以用早期的来重写后面的:

fun apply2 f a = f (apply f a)
fun apply3 f a = f (apply2 f a)
fun apply4 f a = f (apply3 f a)

我们甚至可以重写apply:

fun apply f a = f (apply0 f a)

记住之前apply的定义,它们是等价的:

fun apply f a = f a

那么,apply0 应该是什么?

fun apply0 f a = ...

【讨论】:

    【解决方案2】:

    这个算法的基本情况是什么?即递归终止的n 的值是多少?当它终止时你返回什么?想想如果f 不应用于x,你想要返回什么。在您的示例中,如果 fnc 应用于 10 零次,应该返回什么?

    fun compound n f =
      (* If n equals the termination value, then return the base case*)
      if n = ?
      else fn x => f(compound (n-1) f(x));
    

    这里有一个模式存在于递归算法的基本情况中。例如,没有元素的列表的总和是多少?或者,没有元素的列表的长度是多少?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 2017-07-16
      • 2018-05-30
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多