NickO
NickO

Reputation: 741

Racket, execute arbitrary function with arbitrary number of parameters

I would like to define a general function along the lines of:

(define (gen-func other-func)
   (other-func))

that will execute the function passed to it. But, I want to be able to pass parameters with other-func. So if I had:

(define (add-test a b c d)
    (+ a b c d))

and

(define (divide-test a b)
    (/ a b))

then I could do

(gen-func divide-test 3 4)

and

(gen-func add-test 1 2 3 4)

but it would actually do what I want (which is execute the function with passing along the arbitrary number of arguments). This is part of my process of learning Racket.

Upvotes: 1

Views: 744

Answers (1)

Terje D.
Terje D.

Reputation: 6315

What you are looking for is apply and rest arguments:

(define (gen-func func . args)
   (apply func args))

The dotted parameter list func . args results in all args after the first one being collected into the list args. The reason that this works is that (func . args) is the same as (cons func args), so when the function is called, func is set to (car arglist), and args are set to (cdr arglist) which is the list of arguments after the first one.

Upvotes: 5

Related Questions