[previous] [up] [next]     [contents] [index]
Next: Invoking Units Up: Creating Units Previous: Creating Units

Examples

The unit defined below imports and exports no variables. Each time it is invoked, it prints and returns the current time in seconds:[footnote]

  (define f1@
     (unit
       (import) (export x)
       (define x (current-seconds))
       (display x) (newline) x))

The expression below is syntactically invalid because current-date is not a built-in procedure:

  (define f2-bad@
     (unit
       (import) (export x)
       (define x (current-date))
       (display x) (newline) x))
but the next expression is valid because the unit expression is in the scope of the let-bound variable:
  (define f2@
     (let ([current-date current-seconds])
       (unit
         (import) (export x)
         (define x (current-date))
         (display x) (newline) x)))

The following units define two parts of an interactive phone book:

  (define database@
    (unit (import show-message)
          (export insert lookup)
      (define table (list))
      (define insert
        (lambda (name info)
          (set! table (cons (cons name info) table))))
      (define lookup
        (lambda (name)
          (let ([data (assoc name table)])
            (if data
                (cdr data)
                (show-message "info not found")))))
       insert))

  (define interface@
    (unit (import insert lookup make-window make-button)
          (export show-message)
      (define show-message
        (lambda (msg) ...))
      (define main-window
        ...)))
In this example, the database@ unit implements the database-searching part of the program, and the interface@ unit implements the graphical user interface. The database@ unit exports insert and lookup procedures to be used by the graphical interface, while the interface@ unit exports a show-message procedure to be used by the database (to handle errors). The interface@ unit also imports variables that will be supplied by an architecture-specific graphics toolbox.



PLT