Reputation:
Everytime I see functions returning functions, the returned function is always a lambda. I'm wondering if I can have my function return a function that has a name to it.
Upvotes: 1
Views: 99
Reputation: 31145
Here is a small example.
#lang racket
(define (fun1) "Function 1")
(define (fun2) "Function 2")
(define (number->function n)
(cond
[(= n 1) fun1]
[(= n 2) fun2]
[else (error 'number->function "expected 0 or 1 as input")]))
(number->function 1)
((number->function 1))
The output is:
#<procedure:fun1>
"Function 1"
Upvotes: 0
Reputation: 27424
The syntax that you are trying to use is correct, simply use the name of the inner function as value returned by the outer function. For instance you can write:
(define (incrementer x)
(define (adder y)
(+ x y))
adder)
(define incrementer-by-1 (incrementer 1))
(define incrementer-by-2 (incrementer 2))
(incrementer-by-1 3)
(incrementer-by-1 10)
(incrementer-by-2 15)
As a comment says, keeping in mind that (define (f x) y)
is just an abbreviation for (define f (lambda(x) y))
, the previous function is equivalent to:
(define (incrementer x)
(lambda (y)
(+ x y)))
As another example, you can return a function which was previously defined:
(define (make-positive x)
(abs x))
(define (make-negative x)
(- (abs x)))
(define (same-signer x)
(if (>= x 0)
make-positive
make-negative))
((same-signer 3) -2)
Upvotes: 5