Reputation: 7995
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
Reputation: 235984
To remove all the lambdas in the expression you can do this:
(define f (lambda (x) x))
to this equivalent form: (define (f x) x)
letrec
expression with an internal definitionlambda
in the last line with another internal definition, naming it and calling it at the endlambda
, 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 lambda
s are not really eliminated, they're still there under the hood - hidden behind some syntactic sugar.
Upvotes: 4
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