Smajl
Smajl

Reputation: 7995

scheme using lambda

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?

Upvotes: 4

Views: 397

Answers (2)

Óscar López
Óscar López

Reputation: 235984

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.

Upvotes: 4

soegaard
soegaard

Reputation: 31147

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.

Upvotes: 2

Related Questions