[plt-scheme] Am I being required or...?

From: Eli Barzilay (eli at barzilay.org)
Date: Sun Mar 28 06:27:39 EDT 2010

On Mar 28, Synx wrote:
> How would I test if the current module being run has been required
> from another module, or was directly executed by mzscheme, mred or
> drscheme?  For instance (require "some-module.ss") and ($ mzscheme
> some-module.ss) would both load the module, so if I had an example
> program running with ($ mzscheme some-module.ss) it would also run
> for every other program that required the darn thing.

Behaving the same in both cases is a feature.

> I've resorted to various hacks in the past such as making a
> do-example-for-some-module.ss file (and trying to remember to update
> it along with some-module.ss), or providing a "main" procedure for
> the -m switch (which requires tons of (except-in) require
> clauses). But is there a way to definitively /do/ it, that is have a
> program in a module conditionally execute certain code depending if
> that module has been required via (require) or it has been run from
> scratch as the file?

You could:

* Define a macro that requires everything except for `main' -- similar
  to `except-in' but one that works even when `main' is not provided
  by the required module.  Then you can have your own `require' macro
  that always wraps that around all requires.

* Use a different main name for each file, then in the shell
  trampoline use something like:

    echo mzscheme -t "$0" -e "($0)" -- "$@"

* Have some macro that looks like this:

    (define mains (make-hash))
    (define-syntax-rule (main-begin body ...)
      (hash-set! mains the-source-file (lambda () ...)))

  where `the-source-file' is actually getting the source path of the
  macro use (so it actually can't be done with `define-syntax-rule'),
  then write a `run' script that expects a file, requires it, and runs
  the appropriate thunk -- something like:

    (require a b c d)
    (define (main file)
      ((hash-ref mains file)))

  and use this file like this:

    mzscheme run b

  (So this is similar to the previous trick only done in scheme.)

          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                    http://barzilay.org/                   Maze is Life!

Posted on the users mailing list.