Philip Rego
Philip Rego

Reputation: 648

Scheme - How do I return a function?

This function is displaying the correct thing, but how do I make the output of this function another function?

 ;;generate an Caesar Cipher single word encoders
 ;;INPUT:a number "n"
 ;;OUTPUT:a function, whose input=a word, output=encoded word
 (define encode-n
   (lambda (n);;"n" is the distance, eg. n=3: a->d,b->e,...z->c
     (lambda (w);;"w" is the word to be encoded
       (if (not (equal? (car w) '())) 
           (display (vtc (modulo (+ (ctv (car w)) n) 26)) ))
       (if (not (equal? (cdr w) '())) 
           ((encode-n n)(cdr w))  )     
  )))

Upvotes: 0

Views: 5110

Answers (1)

Óscar López
Óscar López

Reputation: 235984

You're already returning a function as output:

(define encode-n
  (lambda (n)
    (lambda (w) ; <- here, you're returning a function!
      (if (not (equal? (car w) '())) 
          (display (vtc (modulo (+ (ctv (car w)) n) 26))))
      (if (not (equal? (cdr w) '())) 
          ((encode-n n)(cdr w))))))

Perhaps a simpler example will make things clearer. Let's define a procedure called adder that returns a function that adds a number n to whatever argument x is passed:

(define adder
  (lambda (n)
    (lambda (x)
      (+ n x))))

The function adder receives a single parameter called n and returns a new lambda (an anonymous function), for example:

(define add-10 (adder 10))

In the above code we created a function called add-10 that, using adder, returns a new function which I named add-10, which in turn will add 10 to its parameter:

(add-10 32)
=> 42

We can obtain the same result without explicitly naming the returned function:

((adder 10) 32)
=> 42

There are other equivalent ways to write adder, maybe this syntax will be easier to understand:

(define (adder n)
  (lambda (x)
    (+ n x)))

Some interpreters allow an even shorter syntax that does exactly the same thing:

(define ((adder n) x)
  (+ n x))

I just demonstrated examples of currying and partial application - two related but different concepts, make sure you understand them and don't let the syntax confound you.

Upvotes: 8

Related Questions