Reputation: 209
What is it in scheme? How can we use it ?
scm> (define (x) 100)
x
scm> (x)
100
scm> x ; When we "called" x, it return (lambda () 100). what is it ?
(lambda () 100)
Upvotes: 0
Views: 567
Reputation: 1
(define (x) 100)
is equivalent to (define x (lambda () 100))
.
The first syntax is actually a syntactic sugar of the second. Both define a procedure.
When you use x
, the Scheme interpreter will return you x
itself. In this case, x
is a lambda expression.
When you use (x)
, you are calling a procedure named x
. The scheme interpreter will apply what's inside x
, in this case, a lambda expression, and return you the return value.
To use lambda, consider lambda expression as an operator.
So ((lambda (<arg-list>) <body>) <parameter-list>)
Or, if you define a lambda expression to a variable, take the variable as the operator, for example, as what you do,
(define x
(lambda () 100))
(x)
Upvotes: 0
Reputation: 48775
(define (x) 100)
is the same as:
(define x ; define the variable named x
(lambda () ; as a anoymous function with zero arguments
100)) ; that returns 100
x ; ==> #<function> (some representation of the evaluated lambda object, there is no standard way)
(x) ; ==> 100 (The result of calling the function)
You might be more in to Algol languages so here is the same in JavaScript:
function x () { return 100; }
is the same as:
var x = // define the variable named x
function () { // as the anonymous function with zero arguments
return 100; // that returns 100
};
x; // => function () { return 100; } (prints its source)
x(); // => 100 (the result of calling the function)
Beginners sometimes add parentheses around variables like ((x))
and it is equivalent to writing x()()
in Algol languages. Thus x
must be a function of zero arguments that will return a function of zero arguments in order to work.
Upvotes: 5