Search code examples
schemeracketmit-scheme

Scheme Lambda? What is it?


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)

Solution

  • (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.