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

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

问题描述

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

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) (xx)) 是一个调用参数的函数,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) (xx)),是给 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天全站免登陆