schemeracketdr.racket

# Trying to write a function that returns another function, but Racket says my lambda is not a function definition?

Programming in racket, I am trying to write a function that takes a single integer, and returns a function that increments that integer by another integer. For example:

``````((incnth 5) 3) --> 8

((incnth 3) -1) --> 2
``````

Unfortunately I don't seem to understand lambda functions still, because my code keeps saying that my lambda is not a function definition. Here is what I wrote.

``````(define (incnth n)
(lambda (f) (lambda (x) (+ n x))))
``````

Solution

• You have one more `lambda` than it's needed. If I understand correctly, the idea is to have a procedure that creates procedures that increment a number with a given number. So you should do this:

``````(define (incnth n) ; this is a procedure
(lambda (x) (+ n x))) ; that returns a lambda
``````

The returned `lambda` will "remember" the `n` value:

``````(define inc2 (incnth 2))
``````

And the resulting procedure can be used as usual, with the expected results:

``````(inc2 40)
=> 42
((incnth 5) 3)
=> 8
((incnth 3) -1)
=> 2
``````