Search code examples
syntaxschemeracketparentheses

Scheme (DrRacket) syntax - parentheses


Let's take a look at the following functions:

(define Increment1 (λ(x)(+ x 1)))
(define (Increment2)
    (define (inc2 x)(+ x 1))
    inc2)

They both return functions which increments x.

Question 1: Given the code:

(define Func Increment2)
(Func 2)

Why do I get an error? (Expected number of arguments = 0, given = 1), While the code

(define Func2 (Increment2))
(Func2 2)

will work and will return a 3. Why is that?

Question 2: Why when defining a function with a lambda, we do not need to wrap it with parentheses? (case Increment1) On the other hand, why do we wrap a function name with parentheses when not using a lambda? (case Increment2)

Question 3: Let's define a function (define Func3 (λ(F x)(F x))).

Why would (Func3 Increment1 2) will work but (Func3 Increment2 2) will fail? (same error as in Question 1).

Thank you.


Solution

  • Increment2 is a function whose return value is a function. Therefore, you need to call Increment2 to get its return value, which is a function.

    Looking at your second listing:

    (define Func2 (Increment2))
    (Func2 2)
    

    We notice that Func2 is the return value of Increment2 which is a function. Therefore you can call it. So Increment2 points to a function that takes 0 arguments, however calling it returns a function that takes one argument.

    For your second question, lambda is an anonymous function. So (define Func3 (λ(F x)(F x))) is a variable definition, where you bind the variable Func3 to an anonymous function, hence, you are naming it and it will act as a regular function.

    In fact, you’ve just discovered that the (define (fun args) ...) syntax is syntactic sugar for binding a variable to an anonymous function.

    As for your third question you should be able to answer it if you understand my answer to your first question.