Next: , Previous: , Up: dynamic environment   [Index]


D.2 Parameters: the archetype of state in the dynamic environment

Parameters are the perfect example of using the dynamic environment to define a state that is “local” to the dynamic extent of a function call; iklib parameters, for details.

The following example shows how in a call:

(with-exception-handler ?handler ?thunk)

the ?handler is called in the dynamic environment of the call to ?thunk, so that it can access the dynamic environment that contributed to cause the exception:

(import (vicare))

(define parm
  (make-parameter #f))

(parametrise ((parm 'outer-parm))
  (with-exception-handler
      (lambda (E)
        (parm))
    (lambda ()
      (parametrise ((parm 'inner-parm))
        (raise-continuable 2)))))
⇒ inner-parm

The following example shows how parametrise causes the value of the parameter to be “local” to a coroutine:

#!vicare
(import (vicare)
  (only (vicare checks)
        with-result
        add-result))

(define-syntax dotimes
  (syntax-rules ()
    ((_ ?count . ?body)
     (do ((i 0 (+ 1 i)))
         ((= i ?count))
       . ?body))
    ))

(define parm
  (make-parameter #f))

(define (doit name init)
  (parametrise ((parm init))
    (coroutine
        (lambda ()
          (dotimes 5
            (add-result (list name (parm)))
            (parm (++ (parm)))
            (yield))))))

(with-result
   (doit 'one  0)
   (doit 'two 10)
   (finish-coroutines)
   1)
⇒ (1 ((one 0) (two 10)
       (one 1) (two 11)
       (one 2) (two 12)
       (one 3) (two 13)
       (one 4) (two 14)))