簡體   English   中英

Scheme中lambda表達式的評估順序

[英]Order of the evaluation of lambda expressions in Scheme

Dr. Racket用戶。

這有兩個表達式:

((lambda(x)(+ x 1))3)

((lambda(x)(+ x 1)2)3)

第一個是lambda表達式,它接受一個輸入並將其增加1.因此它需要3作為其操作數並使(lambda(3)(+ 3 1)等於4。

第二個對我來說非常模棱兩可,因為它評估為2,我無法理解其評估的順序。 我知道它必須用括號改變順序,但我無法理解。 顯然它甚至沒有將“1”和“x”加起來只是出於某種原因產生2作為輸出。 我錯過了對評估的一些基本了解。 提前致謝!

如Racket 文檔中所述

函數定義可以包含函數體的多個表達式。 在這種情況下, 調用函數時返回最后一個表達式的值 其他表達式僅針對某些副作用進行評估,例如打印。

例如:

(define (f x)
  (+ 1 1)              ;; evaluates to 2, but not returned    
  (= 3 4)              ;; evaluates to false, but not returned
  0                    ;; evaluates to 0, but not returned
  1000                 ;; evaluates to 1000, but not returned
  pi                   ;; evaluates to pi, but not returned
  "I am a string")     ;; last expression; evaluates and returns "I am a string"

(f 10)
=> "I am a string"
(f 'okay)
=> "I am a string"
(f pi)
=> "I am a string"

在你的最后一個lambda中發生了同樣的事情,其中​​:

((lambda (x) (+ x 1) 2) 3)
=> ((lambda () (+ 3 1) 2))
=> ((lambda () 4 2))   ;; last expression is 2, so output 2
=> 2

從所有衍生形式本體lambda從左至右,以便如在評價begin 除最后一個表達式之外的所有表達式僅針對副作用進行評估,而最后一個表達式的結果將是您的函數的結果:

((lambda (x)
   (+ x 1) ; not in tail position. no effect so it's dead code
   2)      ; the evaluation of 2 will be the result every time
 3) ; argument, only used by dead code.

它實際上產生了總和,然后扔掉它來評估最后一個表達式。 只有善用死碼才能在冬天保暖。 在身體中更明智地使用更多表情的一個例子:

(define (hypopotemus a b)
  (define (square x)                ; Not in tail position, creates 
    (* x x))                        ; a function as side effect.
  (sqrt (+ (square a) (square b)))) ; Tail expression calculates the result

因為這提到了評估順序。 雖然函數的參數在所有Scheme報告中的#lang racket中嚴格從左到右進行評估,例如#!r6rs ,但實現(如racket)可以選擇任何順序。 例如。

((lambda (a b c) (display "d")) 
 (display "a")
 (display "b")
 (display "c")

雖然上面的代碼總是在#lang racket打印“abcd”,但它只是Scheme中6種可能結果中的一種,因為你不知道參數在第一個,中間和最后被評估的順序,並且打印將在評估順序中發生。 我知道球拍當然會從左到右評估他們的方案代碼,而Ikarus則按照相反的順序進行評估。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM