Odoc: Support for Examples

In writing documentation, I like to include usage examples in addition to plain-language descriptions of what the code does. An example from my own code:

(** [roll_imposter card] will change card's rank to [Imposter (Some n)] if it's
    [Imposter None], and otherwise will return the card unchanged.

    Examples:
    {[
let card = Card.create Red (Imposter None) in
assert (card != roll_imposter card);
assert (match card.rank with
        | Imposter i -> Option.is_some i
        | _ -> false);

let card = Card.create Red (Value 1) in
assert (card = roll_imposter card);

let card = Card.create Red (Imposter (Some 1)) in
assert (card = roll_imposter card);
    ]}
    *)
let roll_imposter (card : Card.t) : Card.t =
  ...

I’ve written Examples: above, but maybe this could be @examples {|...|}.

I think supporting this with a tag in odoc would be a benefit for displaying the examples (can format it nicely) and would allow for odoc and others to use the examples in analysis or documentation tests in the future.

My inspiration for this comes from Rust’s rustdoc, which parses example blocks from markdown docstrings and is able to use them for testing and specialized display in doc.rust-lang.org pages.

2 Likes

See GitHub - realworldocaml/mdx: Execute code blocks inside your documentation

4 Likes

You could also take some inspiration from Haskell, where examples are collapsed by default so they aren’t as noisy.
I’m pretty sure odoc should support this with @closed tags, although I’ve never actually seen it in the wild.
Nevermind, @closed is just for includes. It would be very nice to have a feature for this that works like it does in haddock though!

3 Likes