简体   繁体   中英

What does the following code in Scheme return

I am trying to understand why this certain scheme code returns the value of 36. I do not understand exactly how the variables bind.

(((lambda (fn)
    (lambda(x)(fn (fn x))))
  (lambda (x) (* x 3)))
 4)

If someone could provide a comprehensive traversal of this code, it would be very helpful in my studies. Thank you.

Use substitution principle to evaluate the code. Having your code indented nicely as you have done is helpful because you can easily see which expressions can be plugged into the lambdas

(((lambda (fn) (lambda(x) (fn (fn x)))) (lambda (x) (* x 3))) 4)

First, we will substitute in (lambda (x) (* x 3)) for fn

((lambda(x) ((lambda (x) (* x 3)) ((lambda (x) (* x 3)) x)))  4)

Now we will substitute in 4 for the outermost x

((lambda (x) (* x 3)) ((lambda (x) (* x 3)) 4))

Now we will substitute in 4 in for x on the right-side lambda

((lambda (x) (* x 3)) (* 4 3))

Evaluate (* 4 3)

((lambda (x) (* x 3)) 12)

Substitute 12 for x

(* 12 3)

Evaluate

36

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM