T. Thomas
T. Thomas

Reputation: 680

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. 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)

Upvotes: 3

Views: 6614

Answers (1)

daniel gratzer
daniel gratzer

Reputation: 53881

Here's the problem, you are trying to apply F to the return of applyNtimes but think for a second, what does that return? a lambda.

This means in your case, we're trying to apply cdr to a lambda, whoops.

In order to get the value of this lambda to actually use it, we have to invoke it. 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. Since in our case F is really cdr we'd better give it some form of pair.

In this code the 'Something' is the result of applying (applyNTimes F (- n 1)) to 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

(lambda (x) x)

Which really turns this whole thing into

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

Which is our desired applyNtimes function.

Upvotes: 4

Related Questions