#lang scribble/doc @(require "common.ss" scribble/eval) @title[#:tag "eval"]{Examples and Tests} In the documentation for a function or syntactic form, concrete examples help a reader understand how a function works, but only if the examples are reliable. Ensuring that examples are correct is a significant burden in a conventional approach to documentation, because the example expressions must be carefully checked against the implementation (often by manual cut and paste), and a small edit can easily introduce a bug. The @scheme[examples] form of the @schememodname[scribble/eval] library typesets an example along with its result using the style of a read-eval-print loop. For example, @scr:code-block|{ @examples[(/ 1 2) (/ 1 2.0) (/ 1 +inf.0)] }| @no-indent produces the output @nested{ @examples[(/ 1 2) (/ 1 2.0) (/ 1 +inf.0)] } Since building the documentation runs the examples every time, the typeset results are reliable. When an author makes a mistake, or when an implementation changes so that the documentation is out of sync, the example remains correct---though it may not reflect what the author intended. For example, if we misspell @scheme[+inf.0] in the example, then the output is still accurate, though unhelpful in describing the behavior of division: @nested{ @examples[(/ 1 +infinity.0)] } To guard against such mistakes, an example expression can be wrapped with @scheme[eval:check] to combine it with an expected result: @scr:code-block|{ @examples[(eval:check (+ 1 +infinity.0) 0.0)] }| @no-indent Instead of typesetting an error message, this checked example will raise an exception when the document is built, since the expression does not produce the expected result @scheme[0.0]. In this way, documentation source can serve partly as a test suite. Evaluation of example code mingles two phases that we have otherwise worked to keep separate: the time at which a library is executed, and the time at which its documentation is produced. For simple functional expressions, such as @scheme[(/ 1 2)], the separation does not matter, and @scheme[examples] could simply duplicate its argument in both an expression position and a typeset position. More generally, however, examples involve temporary definitions and side-effects. To prevent examples from interfering with each other while building a large document, @scheme[examples] uses a sandboxed environment, for which PLT Scheme provides extensive support@~cite[icfp99-ffkf].