在Scheme中,如何使用lambda创建递归函数? [英] In Scheme, how do you use lambda to create a recursive function?

查看:140
本文介绍了在Scheme中,如何使用lambda创建递归函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Scheme类中,我对不使用define编写递归函数感到好奇.当然,主要的问题是,如果没有名称,则无法在其内部调用函数.

I'm in a Scheme class and I was curious about writing a recursive function without using define. The main problem, of course, is that you cannot call a function within itself if it doesn't have a name.

我确实找到了这个示例:这是仅使用lambda的阶乘生成器.

I did find this example: It's a factorial generator using only lambda.

((lambda (x) (x x))
 (lambda (fact-gen)
   (lambda (n)
     (if (zero? n)
         1
         (* n ((fact-gen fact-gen) (sub1 n)))))))

但是我什至无法理解第一个调用,(lambda(x)(x x)):这到底是做什么的?在哪里输入要获取阶乘的值?

But I can't even make sense of the first call, (lambda (x) (x x)): What exactly does that do? And where do you input the value you want to get the factorial of?

这不是上课的目的,这只是出于好奇.

This is not for the class, this is just out of curiosity.

推荐答案

(lambda (x) (x x))是一个可自行调用参数 x 的函数.

(lambda (x) (x x)) is a function that calls an argument, x, on itself.

您发布的整个代码块都具有一个参数的函数.您可以这样称呼它:

The whole block of code you posted results in a function of one argument. You could call it like this:

(((lambda (x) (x x))
  (lambda (fact-gen)
    (lambda (n)
      (if (zero? n)
          1
          (* n ((fact-gen fact-gen) (sub1 n)))))))
 5)

以5调用它,并返回120.

That calls it with 5, and returns 120.

从最高级的角度考虑这个问题的最简单方法是,第一个函数(lambda (x) (x x)) x 提供对自身的引用,因此现在 x 可以引用本身,因此递归.

The easiest way to think about this at a high level is that the first function, (lambda (x) (x x)), is giving x a reference to itself so now x can refer to itself, and hence recurse.

这篇关于在Scheme中,如何使用lambda创建递归函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆