Warning: This is the manual of the legacy Guile 2.0 series. You may want to read the manual of the current stable series instead.

Next: , Up: Hooks   [Contents][Index]


6.11.6.1 Hook Usage by Example

Hook usage is shown by some examples in this section. First, we will define a hook of arity 2 — that is, the procedures stored in the hook will have to accept two arguments.

(define hook (make-hook 2))
hook
⇒ #<hook 2 40286c90>

Now we are ready to add some procedures to the newly created hook with add-hook!. In the following example, two procedures are added, which print different messages and do different things with their arguments.

(add-hook! hook (lambda (x y)
                    (display "Foo: ")
                    (display (+ x y))
                    (newline)))
(add-hook! hook (lambda (x y)
                    (display "Bar: ")
                    (display (* x y))
                    (newline)))

Once the procedures have been added, we can invoke the hook using run-hook.

(run-hook hook 3 4)
-| Bar: 12
-| Foo: 7

Note that the procedures are called in the reverse of the order with which they were added. This is because the default behaviour of add-hook! is to add its procedure to the front of the hook’s procedure list. You can force add-hook! to add its procedure to the end of the list instead by providing a third #t argument on the second call to add-hook!.

(add-hook! hook (lambda (x y)
                    (display "Foo: ")
                    (display (+ x y))
                    (newline)))
(add-hook! hook (lambda (x y)
                    (display "Bar: ")
                    (display (* x y))
                    (newline))
                    #t)             ; <- Change here!

(run-hook hook 3 4)
-| Foo: 7
-| Bar: 12