2

What is the difference between test1:

(define test1
  (lambda (x) (* x x)))

and test2

(define (test2 x)
  (lambda (x) (* x x)))

Aren't both suppose to be the same. When I test test1 I get an correct answer but test2 returns #<function> or (lambda (a1) ...)

Why is that?

2 Answers 2

1

Test1 is equivalent to

(define (test3 x)
    (* x x))

In test2 you have a lambda too much.

Sign up to request clarification or add additional context in comments.

Comments

1
(define (func-name argument)
  body))

This defines the variable func-name to be a function that takes one argument with body as the content of the function. It is an abbreviation for:

(define func-name (lambda (argument)
  body)

Your second example can thus be written like this:

(define test2 
  (lambda (x)
    (lambda (x) (* x x))))

test2 is a function that returns a function. Also since x is used in both the inner function will never have access to the argument. Imagine this instead:

(define (make-less-than value)
  (lambda (arg)
    (< arg value))

(filter (make-less-than 10) '(9 10 1 11 4 19))
; ==> (9 1 4)

So what happens is that make-less-than returns a function that checks if the passed argument is less than value, in this case 10. It can be reused for other values. For just one time you could just as well have written:

(filter (lambda (v) (< v 10)) '(9 10 1 11 4 19))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.