开发者

Normal order vs Applicative order in Scheme

开发者 https://www.devze.com 2023-02-18 09:23 出处:网络
I got this program: (define a 2) (define (goo x) (display x) (newline) (lambda (y) (/ x y))) (define (foo x)

I got this program:

(define a 2)

(define (goo x)
  (display x) (newline)
  (lambda (y) (/ x y)))

(define (foo x)
  (let ((f (goo a)))
    (if (= x 0)
        x
        (f x))))

and I asked to compare the evaluation 开发者_如何学编程results between the applicative and normal order on the expression (foo (foo 0)).

As I know, in applicative order, (display x) in function goo will print x and after it the program will collapse because y isn't defined. But when I run it in Scheme nothing happens. What is the reason?


(foo 0) evaluates to this code:

(define (goo 2)
  (display 2) (newline)
  (lambda (y) (/ 2 y)))

(define (foo x)
  (let ((f (goo 2)))
    (if (= 0 0)
        0
        ((lambda (y) (/ 2 y)) 0))))

and prints 2, returning 0. While (foo 4) evaluates to:

(define (goo 2)
  (display 2) (newline)
  (lambda (y) (/ 2 y)))

(define (foo 4)
  (let ((f (goo 2)))
    (if (= 4 0)
        4
        ((lambda (y) (/ 2 y)) 4))))

and prints 2, returning 0.5.

0

精彩评论

暂无评论...
验证码 换一张
取 消