In an answer which explains how to convert a number to a list the number->list
procedure is defined as follows:
(define (number->list n)
(let loop ((n n)
(acc '()))
(if (< n 10)
(cons n acc)
(loop (quotient n 10)
(cons (remainder n 10) acc)))))
Here a "named let
" is used. I don't understand how this named let
works.
I see that a loop is defined where the variable n
is equal to n
, and the variable acc
equal to the empty list. Then if n
is smaller than 10 the n
is consed to the acc. Otherwise, "the loop" is applied with n
equal to n/10
and acc
equal to the cons of the remainder of n
/10 and the previous accumulated stuff, and then calls itself.
I don't understand why loop
is called loop (what is looping?), how it can automatically execute and call itself, and how it will actually add each number multiplied by its appropriate multiplier to form a number in base 10.
I hope someone can shine his or her light on the procedure and the above questions so I can better understand it. Thanks.