Next: , Up: iklib modules examples   [Index]


6.36.2.1 Anonymous modules examples

The following example defines an anonymous module, without expressions, and invokes its functions from the enclosing region (which is a top–level program):

(import (vicare))

(module (one two three)
  (define (one)       'one)
  (define (two)       'two)
  (define (three)     (cons 'three (hidden)))
  (define (hidden)    'hidden))

(fprintf (current-error-port)
  "calling anonymous: ~s ~s ~s\n" (one) (two) (three))

the output of the program is:

calling anonymous: one two (three . hidden)

notice that the hidden function is visible inside the module but not in the enclosing region.

The following example defines a module, with expressions, and invokes its functions from the enclosing region (which is a top–level program):

(import (vicare))

(module (one two three)
  (define (one)       'one)
  (define (two)       'two)
  (define (three)     (cons 'three (hidden)))
  (define (hidden)    'hidden)

  (fprintf (current-error-port)
    "defining an anonymous module\n"))

(fprintf (current-error-port)
  "calling anonymous: ~s ~s ~s\n" (one) (two) (three))

the output of the program is:

defining an anonymous module
calling anonymous: one two (three . hidden)

notice how the expressions at the end of a module are evaluated before the expressions at the end of the top–level program.

When a module definition is present at the top–level of a program: trailing expressions at the end of the module definitions are handled like top–level expressions mixed between top–level definitions. We can verify this with the following program:

(import (vicare))

(define a
  (begin
    (fprintf (current-error-port) "before\n")
    (void)))

(module ()
  (fprintf (current-error-port) "module\n"))

(define b
  (begin
    (fprintf (current-error-port) "after\n")
    (void)))

whose output is:

before
module
after

Let’s see, instead, what happens when the module definition is at the top–level of a library, which does not allow mixed definitions and expressions. The following program defines a library using the library syntax:

(import (vicare))

(library (the-demo)
  (export a)
  (import (vicare))
  (define a
    (begin
      (fprintf (current-error-port) "before\n")
      123))

  (module ()
    (fprintf (current-error-port) "module\n"))

  (define b
    (begin
      (fprintf (current-error-port) "after\n")
      (void)))

  (fprintf (current-error-port) "library: ~a\n" a)
  #| end of library |# )

(import (the-demo))
(fprintf (current-error-port) "program: ~a\n" a)

the output is:

before
module
after
library: 123
program: 123

here the module’s trailing expressions are evaluated after all the module’s definitions and before the following library’s definitions and expressions.


Next: , Up: iklib modules examples   [Index]