4

I have a piece of code in scheme that uses several lambdas. It basically returns a number that's in the middle.

(define foo
  (lambda (x)
    (letrec
      ((h (lambda (y z)
        (cond
          ((null? y) 'undefined)
          ((null? (cdr y)) (car z))
          (else (h (cddr y) (cdr z)))))))
  ((lambda (y) (h y y)) x))))

I have to rewrite the code so it doesn't use any lambda. How do I do that?

0

2 Answers 2

4

To remove all the lambdas in the expression you can do this:

  • Replace the procedure definition from this form: (define f (lambda (x) x)) to this equivalent form: (define (f x) x)
  • Replace the letrec expression with an internal definition
  • Replace the lambda in the last line with another internal definition, naming it and calling it at the end
  • Even simpler: notice that you don't really need the last lambda, as is equivalent to directly calling (h x x)

After successively applying each of the above replacements, the procedure ends up looking like this:

(define (foo x)
  (define (h y z)
    (cond
      ((null? y) 'undefined)
      ((null? (cdr y)) (car z))
      (else (h (cddr y) (cdr z)))))
  (h x x))

Notice that the lambdas are not really eliminated, they're still there under the hood - hidden behind some syntactic sugar.

Sign up to request clarification or add additional context in comments.

Comments

2

It depends on the context and what you have been taught. If you post more context, you'll most likely get a better answer.

However, note first, that

(define (foo x) (+ x 1)) 

is equivalent to

(define foo (lambda (x) (+ x 1))).

To get rid of letrec rewrite it to an internal definition.

2 Comments

Thanks, I have managed to simplify the code to:(define (foo x) (letrec ((h (lambda (y z) (cond ((null? y) 'undefined) ((null? (cdr y)) (car z)) (else (h (cddr y) (cdr z))))))) (h x x))) but am not sure how to remove the last lambda (maybe some inner define?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.