简体   繁体   English

Racket博士的Lambda递归

[英]Lambda Recursion in Dr Racket

Im trying to created the function "apply N times" in Dr Racket but Don't know where I'm going wrong. 我试图在Dr Racket创建“应用N次”功能,但不知道我哪里出错了。 My code seems to be correct but clearly I'm missing something. 我的代码似乎是正确的,但显然我错过了一些东西。 Printed below is the code and the error I'm getting. 下面打印的是代码和我得到的错误。

(define (applyNtimes F n)
  (lambda (x)
    (if (= n 0) x 
        (F (applyNtimes F (- n 1))))))

(define cdr3 (applyNtimes cdr 3))

(cdr3 '(1 2 3 4 4 5))

and This is the error I'm getting: 这是我得到的错误:

cdr: contract violation
  expected: pair?
  given: #

the expected output should be 预期的产出应该是

(4 4 5)

Here's the problem, you are trying to apply F to the return of applyNtimes but think for a second, what does that return? 这是问题所在,你试图将F应用于applyNtimes的返回,但想一想,这会带来什么回报呢? a lambda . 一个lambda

This means in your case, we're trying to apply cdr to a lambda, whoops. 这意味着在你的情况下,我们试图将cdr应用于lambda,呐喊。

In order to get the value of this lambda to actually use it, we have to invoke it. 为了获得这个lambda的值实际使用它,我们必须调用它。 Doing this is pretty easy, just changing 这样做很容易,只是改变

(F (applyNtimes F (- n 1))))))

to

(F ( (applyNtimes F (- n 1)) ;;Get the Lambda
     x))))) ;; and apply it to x

To understand this let's break it apart, first we apply F to something. 为了理解这一点,让我们分开,首先我们将F应用于某事。 Since in our case F is really cdr we'd better give it some form of pair. 因为在我们的情况下F真的是cdr我们最好给它一些形式的对。

In this code the 'Something' is the result of applying (applyNTimes F (- n 1)) to x . 在这段代码中,'Something'是将(applyNTimes F (- n 1))应用于x

Well this leads us to some recursion, where what we're really doing is 这导致我们进行一些递归,我们真正在做的是

(F (F (F ... ((applyNTimes F (- n whatever)) x))))

Ok so how does this recursion end? 那么这个递归怎么结束呢? Well when (- n whatever) is 0, we return the lambda 那么当(- n whatever)是0时,我们返回lambda

(lambda (x) x)

Which really turns this whole thing into 这真的把这一切都变成了

(F (F (F (F (F (F x)))))) (F(F(F(F(F(F x))))))

Which is our desired applyNtimes function. 这是我们想要的applyNtimes函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM