简体   繁体   中英

explanation of lambda expression in scheme

I was wondering if anyone could explain this lambda expression and how the output is derived. I put it into the interpreter and am getting ((2) 2) . I'm just not sure why it's giving me that instead of just (2 2) .

 ((lambda x (cons x x)) 2)

The expression (lambda x (cons xx)) produces a function; the function puts all arguments into a list x ; the function returns (cons xx) .

Your expression calls the above function with an argument of 2 . In the function x is (2) (a list of all the arguments). The function (cons '(2) '(2)) returns ((2) 2)

(cons x x)

is not the same as

(list x x)

since it produces dotted pairs, eg (cons 2 2) returns (2 . 2) .

But when the right side of a dotted pair is a list, the whole thing is a list. (lambda x expr) takes an arbitrary number of arguments, puts them in a list x , so that's (2) here. The dotted pair ((2) . (2)) is printed as ((2) 2) per Lisp conventions.

Yep, you've ran off the deep end of scheme.

You've stublled across the notation that allows you to write a function that accepts zero or more arguments. (any number really)

(define add-nums
 (lambda x
  (if (null? x)
      0
      (+ (car x) (apply add-nums (cdr x))))))

(add-nums 1 87 203 87 2 4 5)

;Value: 389

If you just want one argument you need to enclose x in a set of parenthesis.

And you want to use

(list xx)

or

(cons x (cons x '())

as the function body, as a properly formed list will have an empty list in the tail position.

You probably wanted to write:

((lambda (x) (cons x x)) 2)

(note the brackets around x ).

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