[英]About "Frames as Repository of Local State"
SICP, 第 3.2.3 節中的練習 3.10 顯示以下內容作為先前定義make-withdraw
的替代方法:
(define (make-withdraw initial-amount)
(let ((balance initial-amount))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))))
並規定我們
使用環境 model 來分析這個
make-withdraw
的替代版本,繪制類似上面的圖來說明交互(define W1 (make-withdraw 100)) (W1 50) (define W2 (make-withdraw 100))
)) ) is syntactic sugar for ((lambda ( ) ) )
.然而,在上述請求之前,文本回憶起(let (( )) )
是((lambda ( ) ) )
的語法糖。
現在我猜這個建議意味着我應該分析這個版本的make-withdraw
:
(define (make-withdraw initial-amount)
((lambda (balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
initial-amount))
或者,甚至更好(基於過程定義語法只是底層隱式lambda
表達式的語法糖,來自第 3.2.1 節):
(define make-withdraw
(lambda (initial-amount)
((lambda (balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
initial-amount)))
在這里我看到 3 lambda 程序,而在這個和這個解決方案(非官方;我不知道官方解決方案)中只顯示了兩個程序。 例如,這是后一種解決方案:
; After (define W1 (make-withdraw 100))
global env
------------------
| |<--- env: global env
| | parameters: initial-amount
| make-withdraw: ----> body:
| | ((lambda (balance)
| | (lambda (amount)
| | (if (>= balance amount)
| | (begin (set! balance (- balance amount))
| | balance)
| | "Insufficient funds"))) initial-amount)
| |
| | E1
| | -----------------------
| |<----| initial-amount: 100 |
| | -----------------------
| | /\
| | E2 |
| | ----------------
| | | balance: 100 |
| | ----------------
| | /\
| | |
| | env: E2
| | parameters: amount
| W1: ---------------> body:
| | (if (>= balance amount)
| | (begin (set! balance (- balance amount))
| | balance)
| | "Insufficient funds")
------------------
而我會想象一個帶有parameters: balance
和body: (lambda (amount) …)
也被繪制,因為那是在E2
中運行的(臨時?) lambda ( balance
綁定到initial-amount
,而不是100
,這反過來又綁定到E1
中的100
)以生成最終綁定到W1
的過程。
我對么? 如果不是,你能解釋一下為什么嗎?
當(make-withdraw 100)
被調用時,它會構建一個initial-amount
綁定到100
的環境(這是圖中的E1
)。 It then immediately calls another function in this environment : that function constructs a child environment in which balance
is bound to 100
, which is E2
in the diagram, and returns a third function defined in that environment, which is thus the return value of make-withdraw
。
所以W1
現在綁定到第三個 function,其環境是E2
。 構造E2
的第二個 function 已被調用並返回其值(第三個函數):它不再出現在圖片中。
這就是它不再存在的原因。
我不確定它是否有幫助,但是如果make-withdraw
根本不存在,考慮一下環境圖片可能會很有用,因為它在W1
點的真正虛假噪聲已被定義(顯然不是在現實生活中,您可能想在其中創建多個帳戶:):
(define W1 ((λ (initial-amount)
;; this function was `make-withdraw`
((λ (balance)
;; this function was `let`
(λ (amount)
;; this is what W1 will end up being
(if (>= balance amount)
(begin
(set! balance (- balance amount))
balance)
"Insufficient funds")))
initial-amount))
100))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.