Can someone explain me what's happening with the two lambda statements in the following code?
(define (remove x ls)
(if (null? ls)
'()
(let ((h (car ls)))
((if (eqv? x h)
(lambda (y) y)
(lambda (y) (cons h y)))
(remove x (cdr ls))))))
What is the 'y' in the above code?
Depending on the if
's condition, we're returning one or the other lambda
and then immediately applying it (notice the double opening parentheses to the left of the if
). The first lambda
returns the result of calling the recursion, the second lambda
cons
es an element to the result of calling the recursion, either way the recursion gets called. The y
is just the parameter name for the lambda
s, which gets bound to the value of (remove x (cdr ls))
. The whole thing is equivalent to this, and in fact it should be written like this, not in its current, overly complicated form:
(define (remove x ls)
(if (null? ls)
'()
(let ((h (car ls)))
(if (eqv? x h) ; using `equal?` would be a better idea
(remove x (cdr ls))
(cons h (remove x (cdr ls)))))))