racket Functions The `apply` function


Example

If you have a list, and you want to use the elements of that list as the arguments to a function, what you want is apply:

> (apply string-append (list "hello" " " "and hi" " " "are both words"))
"hello and hi are both words"
> (apply + (list 1 2 3 4))
10
> (apply append (list (list "a" "b" "c") (list 1 2 3) (list "do" "re" "mi")))
(list "a" "b" "c" 1 2 3 "do" "re" "me")

apply takes two arguments. The first argument is the function to apply, and the second argument is the list containing the arguments.

An apply call like

(apply + (list 1 2 3 4))

Is equivalent to

(+ 1 2 3 4)

The major advantage of apply is that it works on arbitrary computed lists, including appended lists and lists that come from function arguments.

> (apply + (append (list 1 2 3 4) (list 2 3 4)))
19
> (define (sum lst)
    (apply + lst))
> (sum (list 1 2 3 4))
10
> (sum (append (list 1 2 3 4) (list 2 3 4)))
19

For more information and examples, see The apply function in the Racket Guide.