0

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))))
double-beep
  • 5,031
  • 17
  • 33
  • 41
BestInTOWN
  • 33
  • 4

1 Answers1

1

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
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Thanks! That's what I was trying to run originally actually, but Dr.Racket was still saying my lambda was not a function definition. Turns out I needed to choose language "Intermediate Student with lambda". I was previously on just "Intermediate Student". – BestInTOWN Mar 31 '21 at 18:17
  • @BestInTOWN The student languages are neither Scheme nor Racket. You should specify in your question which language you are using. My guess is `#lang racket` for only racket tag while with `scheme` tag I assume any of the RNRS report languages eg `#!r6rs`. – Sylwester Mar 31 '21 at 22:53
  • 1
    @Sylwester I don't see the issue with tagging Racket, isn't the student language just Racket with limitations? I tagged Scheme because my professor actually had the class learn the student language from a Scheme tutorial. So I figured people who know scheme would also be able to help me. Overall and most importantly, I just wanted to make sure I understood lambda expressions. Which is part of Racket and Scheme. – BestInTOWN Apr 01 '21 at 23:09
  • @BestInTOWN The racket compiler/runtime/IDE supports several languages. One of them Algol60, a completely non lisp language from the 60s not related to racket at all. In fact racket can support languages that are as different as they come. While tagging `racket` as in "I'm using racket" is fine, but when not using `#lang racket` one should always state what one uses to make sure to get the answers for that language. I think this answer focuses on the obvious error with three lambdas rather than it being the wrong language demonstrated this well. – Sylwester Apr 03 '21 at 22:07