本地:从 "outside" 和 "inside" 调用函数?

Local: Calling functions from "outside" and from "inside"?

我可以从 "outside" 调用 内部 local 函数吗?假设我们有函数 A。它调用了一个位于局部函数中的函数。功能 A 不在那个地方。这可能吗?

或者 local 中的函数是否可以调用 local 的 "outside" 函数?

我知道这些论点之一是错误的,但我不记得是哪一个以及为什么。谁能给我解释一下哪一个是正确的,为什么

(球拍)

我认为这会有所帮助

#lang racket

(define (A x)
  (local [(define (localA y)
            (printf "localA ~a ~a\n" x y)
            (printf "i can call B\n")
            ;; here we see localA, A, and B
            (B (+ 1 x)))]
    ;; here we see localA, A, and B
    (localA (* x 2))))     

(define (B x)
  (local [(define (localB y)
            (printf "localB ~a ~a\n" x y)
            (printf "i can call A\n")
            ;; here we see localB, B, and A
            (A (+ 1 x)))]
    ;; here we see localB, B, and A
    (localB (* x 3))))

(A 0)

; localA 0 0
; i can call B
; localB 1 3
; i can call A
; localA 2 4
; i can call B
; localB 3 9
; i can call A
; localA 4 8
; i can call B
; localB 5 15
; i can call A
; localA 6 12
; i can call B
; localB 7 21
; ...

A 无法调用 localBB 无法调用 localA

您不能在其范围之外使用本地绑定,除非您通过向上或向下 funarg 显式公开它们或使用本地闭包改变绑定。示例:

(define (test n)
  (local [(define (helper from acc)
            (if (> from n)
                acc
                (helper (add1 from) (cons from acc))))]
    (helper 1 '())))

(test 5) ; ==> (5 4 3 2 1)

无法从 test-sum 外部访问或调用 helper,因为它是 test-sum 本地的并且未通过或 returned。

(define (upward funarg1 n)
  (local [(define (helper from acc)
            (if (> from n)
                acc
                (helper (add1 from) (cons from acc))))]
    (funarg1 helper)))

(define (test funarg2)
  (funarg2 1 '()))

(upward test 5) ; ==> (5 4 3 2 1)

此处 helper 作为参数传递给回调。此处您正在使本地 helper 可供 test 使用。两者的闭包是不同的,因此 test 没有 n 因为它们不共享任何词法变量。

(define (downward n)
  (local [(define (helper from acc)
            (if (> from n)
                acc
                (helper (add1 from) (cons from acc))))]
    helper))

(define from-helper (downward 5))
(from-helper 1 '())   ; ==> (5 4 3 2 1)

((downward 10) 5 '()) ; ==> (10 9 8 7 6 5)

你是return帮手。全局范围将无法访问 helper 中的 n 但他们可以调用它并且它的工作方式与在内部调用时相同。 helper 中的变量似乎已经死了,因为 downward 完成了,但是 Scheme 保留了词法范围,所以 nhelper 可以从 helper 获得只要它存在。

(define exposed #f)
(define (mutate n)
  (local [(define (helper from acc)
            (if (> from n)
                acc
                (helper (add1 from) (cons from acc))))]
    (set! exposed helper)))

(mutate 5)
(exposed 1 '()) ; ==> (5 4 3 2 1)

这只是向下函数的变体。它不是 return 而是改变全局(或词法)变量 exposed ,在 (mutate 5) 完成它之后,将它作为全局、词法或自由变量的代码将能够调用事物。

任何新作用域都会在其封闭作用域内创建嵌套

范围区域中的任何标识符也在封闭范围内,并且可以在同一范围或其封闭范围内使用任何其他标识符范围。

您不能在其范围之外使用标识符;但是您可以通过从该内部范围返回该值 "upward" 来使用它引用的 value