(define length-it
(lambda (ls)
(length ls 0)))
(define length
(lambda (ls acc)
(if (null? ls)
acc
(length (cdr ls) (+ acc 1)))))
How to use letrec to put the function length within the body of function length-it?
The output should be (length-it '(1 2 3)) -> 3.
Let's start with what we've got:
But actually, since there's also a built-in function called
lengthtoo, let's rename ours tomy-length:and now,
Does this work? To what entity does
init(2)refer? Is itinit(1)?Next,
Now does this work? (be sure to test this in a new, fresh environment, without
my-lengthbeing defined separately there at all).No? Why not?
To what entity does the name
init(3)refer? To what doesmy-length(3)refer? To what does the namemy-length(2)refer? Would it work ifmy-length(2)were referring tomy-length(1)as doesmy-length(3)? Since it doesn't work,my-length(2)must refer to some othermy-lengthdefined above theletbut do we have any more of them anywhere there?So can you make it work? Were you supposed to use
letthere, or that other primitive,letrec? Are the two exactly the same? Probably not, otherwise why would they name the same thing twice? So can we try using the other one there? Would it perhaps makemy-length(2)indeed refer tomy-length(1)as it was supposed to do?Does it work now?