In The Little Schemer book, in Chapter 9, while building a length
function for arbitrary long input, the following is suggested (on pages 170-171), that in the following code snippet (from page 168 itself):
((lambda (mk-length)
(mk-length mk-length))
(lambda (mk-length)
((lambda (length)
(lambda (l)
(cond
((null? l) 0)
(else (add1 (length (cdr l)))))))
(mk-length mk-length))))
the part (mk-length mk-length)
, will never return and will be infinitely applying itself to itself:
Because we just keep applying
mk-length
to itself again and again and again...
and
But now that we have extracted
(mk-length mk-length)
from the function that makeslength
it does not return a function anymore.
Now, to cure this the book suggest:
Turn the application of
mk-length
to itself in our last correct version oflength
into a function.
Like, so:
((lambda (mk-length)
(mk-length mk-length))
(lambda (mk-length)
((lambda (length)
(lambda (l)
(cond
((null? l) 0 )
(else
(add1 (length (cdr l)))))))
(lambda (x)
((mk-length mk-length) x)))))
What I get puzzled by is:
If
(mk-length mk-length)
does not return a function
how we can apply the result of
(mk-length mk-length)
to something, as if it is a function?(lambda (x) ((mk-length mk-length) x))
How wrapping
(mk-length mk-length)
into a function solves the 'never returning' (i.e. infinite recursion) problem? My understanding is, that in:(lambda (x) ((mk-length mk-length) x))
x
will just be passed to infinitely recursive function, which never returns.
(cdr l)
as the argument, and it stops when that becomes null. – Anthropography(mk-length mk-length)
doesn't return a function? The value ofmk-length
is the second lambda-expression, and it returns(lambda (l) ...)
, which is a function. – Anthropography(lambda (l) ...)
gets abstracted away. – Swallowtail