WhizzML Reference Manual

4.4 Procedures

It is possible to apply a procedure to a list of arguments, by means of the procedure apply . In its simplest form, apply takes two arguments: the function to call, and a list of the arguments to use to call it:

(apply <proc> <args-list>)

For example:

(apply + [1 2 3]) ;; => (+ 1 2 3) => 6
(apply list ["a" "b"]) ;; => (list "a" "b") => ["a" "b"]

You can easily see that, in general, (apply list x) evaluates to x for any list value of x.

In general, apply can take multiple arguments besides the procedure to call. The full signature of apply is the following:

(apply proc objarg1 ... list-args) \(\rightarrow \) any

proc must be a procedure and list-args must be a list. apply then calls proc with the elements of the list (concat (list arg1 ...) list-of-args) as the actual arguments.

(define compose
   (lambda (f g)
     (lambda (. args)
       (f (apply g args)))))

 ((compose sqrt *) 12 75)   ;; =>  30

Given a procedure f, one can partially apply it to a list of values and obtain a new procedure of lower arity using the standard procedure partial:

(partial proc objarg1 ...) \(\rightarrow \) procedure

partial takes a procedure proc and fewer than the normal number of arguments to proc, and returns a new procedure that takes a variable number of additional args. When called, the returned function calls proc with objargs1…plus the additional args.

(map (partial + 2) [1 2 3]) ;; => [3 4 5]
(map (partial + 2 4) [1 2 3]) ;; => [7 8 9]

(define prep-ab (partial concat ["a" "b"]))
(prep-ab) ;; => ["a" "b"]
(prep-ab [3 1]) ;; => ["a" "b" 3 1]
(prep-ab ["x" "y"] [false true 2]) ;; => ["a" "b" "x" "y" false true 2]