Why "allow" work for naming internal recursive procedures?

Consider the following implementation of the function for calculating the factorial: [1]

(define fac-tail
  (lambda (n)
    (define fac-tail-helper
      (lambda (n ac)
        (if (= 0 n)
            ac
            (fac-tail-helper (- n 1) (* n ac)))))
    (fac-tail-helper n 1)))

I tried to rewrite using letfor internal definition:

(define fac-tail-2
  (lambda (n)
    (let ((fac-tail-helper-2
            (lambda (n ac)
              (if (= 0 n)
                  ac
                  (fac-tail-helper-2 (- n 1) (* n ac))))))
    (fac-tail-helper-2 n 1))))

There is defineno error, but execution results in:

#;> (fac-tail-2 4)
Error: undefined variable 'fac-tail-helper-2'.
{warning: printing of stack trace not supported}

How can I make a version let?

Schema Version - SISC v 1.16.6

[1] Based on the iterative version factorialin SICP section 1.2.1 http://mitpress.mit.edu/sicp/full-text/book/book-ZH-11.html#%_sec_1.2.1

+3
source share
3 answers

How can I make a let version?

Use letrecinstead let.

+8

R. :


, let , , .

(let ((var expr) ...) body1 body2 ...) 

.

((lambda (var ...) body1 body2 ...)
 expr ...)" [1]

, fac-tail-2 :

(define fac-tail-2
  (lambda (n)
    ((lambda (fac-tail-helper-2)
       (fac-tail-helper-2 n 1)) ;; <== scope where fac-tail-helper-2 is visible.
     (lambda (n ac) ;; this lambda is assigned to fac-tail-helper-2
       (if (= 0 n)
           ac
           (fac-tail-helper-2 (- n 1) (* n ac))))))) ;; <=== problem

, , fac-tail-helper-2, paramenter lambda, , lambda, fac-tail-helper-2.

[1] 2.5, "-" , 4- http://scheme.com/tspl4/start.html#SECTGSLAMBDA

+6

, .

, 3.2 let . http://scheme.com/tspl4/further.html#./further:h2

. , , , , .

(define fac-tail-4
  (lambda (n)
    (let ((fac-tail-helper
            (lambda (fac-tail-helper n ac)
              (if (= 0 n)
                  ac
                  (fac-tail-helper fac-tail-helper (- n 1) (* n ac))))))
      (fac-tail-helper fac-tail-helper n 1))))

let, insead letrec .

(define fac-tail-3
  (lambda (x)
    (let fac-tail-helper ((n x) (ac 1))
      (if (= 0 n)
          ac
          (fac-tail-helper (- n 1) (* n ac))))))

, -.

0

Source: https://habr.com/ru/post/1752920/


All Articles