Caveman
Caveman

Reputation: 2955

Passing a lambda function to a lambda function in Scheme

So I have a little challenge.

I'm trying to program this here:

enter image description here

Which with lambda calculus simplifies to 12.

I have the following Scheme script:

(
    define double (
        lambda x (
            + (car x) (car x)
        )
    )
)

(display 'Debug)
(newline)

(display (double 6))
(newline)


(
    define getTwelve (
        ((
            (lambda x (
                lambda y (
                    (display y)
                    (newline)
                    (x (x y))
                )
            ))
            double
        ) 3)
    )
)



(display getTwelve)

(newline)
(newline)

Which corresponds to this terminal output:

Debug
12
(3)
application: not a procedure;
 expected a procedure that can be applied to arguments
  given: '(#<procedure:double>)
  arguments...:
   '(3)

So of course I thought 'it's because the parameter of double is a list instead of a number' but car y just changes the last line of the terminal output to 3.

I think I'm interpreting the Racket terminal output wrong, but I don't know in which way. There is however the other possibility that passing a lambda function into a lambda function as a parameter is not allowed.

So my question is: Which one is it?

Upvotes: 2

Views: 657

Answers (1)

Barmar
Barmar

Reputation: 780663

Usually the parameter list after lambda should be a list of variables. You only use a single variable without a list if you want to allow a variable number of arguments to the procedure, which isn't the case here. If you do this, each variable will be bound to successive arguments, and you don't need to use car to get the value of the argument. So it should be:

(define double
    (lambda (x) 
        (+ x x)))

If you do this with getTwelve you should get the result you expect.

(define getTwelve
  ((((lambda (x)
       (lambda (y)
         (display y)
         (newline)
         (x (x y))))
     double) 3)))

You also had an extra set of parentheses around the body of the innermost lambda.

DEMO

Upvotes: 2

Related Questions