On this page:
1.1 Disrupt
flip
make-categorical
query
observe!
sample
in-pmf
pmf?
region?
1.2 Bayesian Network
1.3 Dice
1.4 The BLOG Language
1.4.1 Declaration order and random-function domains
1.4.1.1 Shared and independent random choices
1.4.2 Sequential and joint queries
1.4.2.1 Usual sequential queries
1.4.2.2 Multiple separate queries versus one joint query
1.4.3 Lists and matrices
1.4.3.1 When a list becomes a matrix
1.4.3.2 Indexing and scalar conversion
1.4.3.3 Arithmetic and the matrix library
1.4.3.4 Random entries and dimensions
1.4.4 Current limitations
1.4.5 Implementation notes
1.4.5.1 Parsing and normalized expressions
1.4.5.2 Matrix representation
1.4.5.3 Declaration expansion and result conversion
1.5 Bentham
flip
observe!
reward!
expected-utility
9.3

1 Examples🔗ℹ

Roulette enables programmers to build languages that require the use of inference engines. This section gives examples of languages built on top of Roulette to show concretely how this works.

1.1 Disrupt🔗ℹ

 #lang roulette/example/disrupt package: roulette
 #lang roulette/example/disrupt/safe

Disrupt is an example discrete probabilistic programming language built on top of the RSDD inference engine.
> (define first-coin (flip 0.5))
> first-coin

┌─────┬───────────┐

│Value│Probability│

├─────┼───────────┤

│#t   │0.5        │

│#f   │0.5        │

└─────┴───────────┘

The flip construct returns a Boolean where #t has the given probability. Evaluating first-coin at the REPL prints out its probability distribution.
> (define second-coin (flip 0.5))
> (define both-heads (and first-coin second-coin))
> both-heads

┌─────┬───────────┐

│Value│Probability│

├─────┼───────────┤

│#t   │0.25       │

│#f   │0.75       │

└─────┴───────────┘

Now, both-heads is a Boolean that takes on the value #t when both coins are also #t.
> (observe! (not both-heads))
> first-coin

┌─────┬──────────────────┐

│Value│Probability       │

├─────┼──────────────────┤

│#t   │0.3333333333333333│

│#f   │0.6666666666666666│

└─────┴──────────────────┘

Observing both-heads, specifically that it is #f, changes the probability of first-coin. Conditional on both-heads being #f, the probability first-coin being #t is 1/3.

procedure

(flip p [#:region reg]) → boolean?

  p : (real-in 0 1)
  reg : (or/c region? #f) = #f
Returns a Boolean where #t has probability p and #f has probability (- 1 p). Optionally, flip can be given a region to place the newly created value. See query for details.
> (if (flip 1/2) 'a 'b)

┌─────┬───────────┐

│Value│Probability│

├─────┼───────────┤

│'b   │0.5        │

│'a   │0.5        │

└─────┴───────────┘

procedure

(make-categorical distr) → any/c

  distr : (listof (cons any/c (real-in 0 1)))
Returns each first component of pairs in distr with the probability given by the second component.
> (make-categorical `((a . 1/3) (b . 1/3) (c . 1/3)))

┌─────┬──────────────────┐

│Value│Probability       │

├─────┼──────────────────┤

│'c   │0.3333333333333333│

│'b   │0.3333333333333333│

│'a   │0.3333333333333333│

└─────┴──────────────────┘

syntax

(query maybe-option ... body ...+)

 
maybe-option = 
  | #:samples iter
  | #:region reg-id
Returns the probability mass function (PMF) associated with e. In other words, query performs nested inference. See in-pmf for an example of how to use the result of this function. Observations are delimited to the dynamic extent of body. After body has finished, any observations executed during body are forgotten.
> (query (flip 1/2))

(pmf [#t 0.5] [#f 0.5])

The #:samples option runs body expression iter times, producing a probabilistic value according to the sampling distribution. The #:region option binds reg-id to the region associated with the query. A region is a first-class representation of dynamic extent. Each application of flip places its return value in a region. A query marginalizes only over variables in its region. After a region ends, the values associated with that region are considered discarded and their probability cannot be computed.
> (query (flip 1/2))

(pmf [#t 0.5] [#f 0.5])

> (let ([x (flip 1/2)]) (query x))

┌──────────────┬───────────┐

│Value         │Probability│

├──────────────┼───────────┤

│(pmf [#t 1.0])│0.5        │

│(pmf [#f 1.0])│0.5        │

└──────────────┴───────────┘

> (query (query (flip 1/2)))

(pmf [(pmf [#t 0.5] [#f 0.5]) 1.0])

> (query (let ([x (flip 1/2)]) (query x)))

(pmf [(pmf [#t 1.0]) 0.5] [(pmf [#f 1.0]) 0.5])

> (query #:region r (query (flip 1/2 #:region r)))

(pmf [(pmf [#t 1.0]) 0.5] [(pmf [#f 1.0]) 0.5])

procedure

(observe! e) → void?

  e : boolean?
Conditions the current execution on e evaluating to #t.
> (define x (flip 1/2))
> (define y (flip 1/2))
> (and x y)

┌─────┬───────────┐

│Value│Probability│

├─────┼───────────┤

│#t   │0.25       │

│#f   │0.75       │

└─────┴───────────┘

> (observe! x)
> (and x y)

┌─────┬───────────┐

│Value│Probability│

├─────┼───────────┤

│#t   │0.5        │

│#f   │0.5        │

└─────┴───────────┘

procedure

(sample e) → any/c

  e : any/c
Samples a concrete value from the given probabilistic value.
> (sample (flip 1/2))

#f

procedure

(in-pmf e) → stream?

  e : pmf?
Sequence constructor for PMFs.
> (define-syntax-rule (expectation e)
    (for/all ([pmf (query e)])
      (for/sum ([(val prob) (in-pmf pmf)])
        (* val prob))))
> (expectation (if (flip 1/2) 5 10))

7.5

procedure

(pmf? e) → boolean?

  e : any/c
Predicate for PMFs.

procedure

(region? e) → boolean?

  e : any/c
Predicate for regions.

1.2 Bayesian Network🔗ℹ

 #lang roulette/example/bn package: roulette

A Bayesian network is a common kind of probabilistic graphical model that expresses conditional dependencies between variables. These networks are often described in the Bayesian Interchange Format (BIF). There are many such networks freely available online, including in the BNLearn repository. The BN language interprets Bayesian networks written in the BIF.

"cancer.rkt"

#lang roulette/example/bn

 

variable Pollution { type discrete [ 3 ] { low, medium, high }; }

variable Smoker { type discrete [ 2 ] { True, False }; }

variable Cancer { type discrete [ 2 ] { True, False }; }

variable Xray { type discrete [ 2 ] { positive, negative }; }

variable Dyspnoea { type discrete [ 2 ] { True, False }; }

 

probability ( Pollution ) {

  table 0.5, 0.4, 0.1;

}

probability ( Smoker ) {

  table 0.3, 0.7;

}

probability ( Cancer | Pollution, Smoker ) {

  (low, True) 0.03, 0.97;

  (medium, True) 0.03, 0.97;

  (high, True) 0.05, 0.95;

  (low, False) 0.001, 0.999;

  (medium, False) 0.001, 0.999;

  (high, False) 0.02, 0.98;

}

probability ( Xray | Cancer ) {

  (True) 0.9, 0.1;

  (False) 0.2, 0.8;

}

probability ( Dyspnoea | Cancer ) {

  (True) 0.65, 0.35;

  (False) 0.3, 0.7;

}

This Bayesian network is the famous "cancer" example that describes the relationship between several variables and whether a patient has lung cancer. Running this file in DrRacket allows one to explore the network with all the constructs from Disrupt in the interactions area. Additionally, the module exports all the variables, making them available to Disrupt programs via require.

> Cancer

┌──────┬────────────────────┐

│Value │Probability         │

├──────┼────────────────────┤

│'True │0.011629999999999998│

│'False│0.98837             │

└──────┴────────────────────┘

> (observe! (equal? Xray 'positive))
> Cancer

┌──────┬───────────────────┐

│Value │Probability        │

├──────┼───────────────────┤

│'True │0.05028802590551598│

│'False│0.949711974094484  │

└──────┴───────────────────┘

This interaction shows the posterior probability that a patient has lung cancer given that they have a positive X-ray result. Notice that the posterior probability of Cancer only marginally increases with a positive test result. Many people are surprised by this phenomenon, which is known as the base rate fallacy.

1.3 Dice🔗ℹ

 #lang roulette/example/dice package: roulette

Dice is a small discrete probabilistic programming language. It was the first functional language to use knowledge-compilation-based probabilistic inference.

"noisy-or.rkt"

#lang roulette/example/dice

 

let n0  = flip 0.5 in

let n4  = flip 0.5 in

let n1  = if n0 then flip 0.8 else flip 0.1 in

let n21  = if n0 then flip 0.8 else flip 0.1 in

let n22  = if n4 then flip 0.8 else flip 0.1 in

let n33  = if n4 then flip 0.8 else flip 0.1 in

let n2  = (n21 || n22) in

let n31  = if n1 then flip 0.8 else flip 0.1 in

let n32  = if n2 then flip 0.8 else flip 0.1 in

let n3  = (n31  || (n32 || n33)) in

n3

Most programs should run out of the box, but there are a few limitations. A small number of operations are not supported. The implementation does not perform typechecking, so evaluating an ill-typed program is undefined behavior. Functions are not compiled modularly, and evaluation follows the "eager" strategy.

1.4 The BLOG Language🔗ℹ

 #lang roulette/example/blog package: roulette

This implementation supports a subset of BLOG, built on roulette/example/disrupt. Simple BLOG programs should run without modification after starting the file with #lang roulette/example/blog. For example:

"blog-example.rkt"

#lang roulette/example/blog

 

type Person;

distinct Person Alice, Bob;

 

fixed Boolean AlwaysTrue = true;

fixed Boolean IsAlice(Person p) = p == Alice;

 

random Real prob ~ Categorical({0.1 -> 0.5, 0.9 -> 0.5});

 

random Boolean Smokes(Person p) ~ BooleanDistrib(prob);

 

random Boolean Healthy(Person p) ~

  if Smokes(p) then BooleanDistrib(0.4)

  else BooleanDistrib(0.9);

 

 

random Boolean Infected(Person p) ~ BooleanDistrib(prob);

 

random Boolean ExtraHealthy(Person p) ~

  if (exists Person q Infected(q)) then BooleanDistrib(0.2)

  else BooleanDistrib(0.8);

 

obs Smokes(Alice) = true;

 

query (ExtraHealthy(Alice));

Here are the supported features:

  • Declare types with type and objects with distinct. Indexed declarations such as distinct Person P[3]; create three distinct objects, accessible as P[0], P[1], and P[2]. Indices may be arithmetic expressions or finite random values.

  • The fixed declarations define constants or functions with parameters. The random declarations use ~ for a distribution or = for a deterministic dependency. Repeated calls to a random function with the same arguments reuse the same random value.

  • BooleanDistrib(p) returns a Boolean. Bernoulli(p) returns 1 with probability p and 0 otherwise. UniformInt(lo, hi) gives equal probability to every integer between the bounds, including both endpoints. Categorical accepts a map such as Categorical({0 -> 0.25, 1 -> 0.75}) where the probabilities must sum to one. Distribution parameters and the choice of distribution may depend on finite random values.

  • The arithmetic operators are +, -, *, /, ^, %, and unary + and -. The comparison operators are ==, !=, <, <=, >, and >=. The Boolean operators are !, &, |, and =>. The forall and exists quantifiers range over the objects of a declared type.

  • Conditionals are written as if condition then expression else expression. Case expressions use case value in {key -> result, ...}. Branches may return values or distributions. An omitted else or an unmatched case returns null.

  • Supply evidence with obs expression = expression; and query an expression with query expression;. Queries execute sequentially using preceding observations.

  • Query joint distributions with query expression1, expression2;. Each outcome is a tuple in expression order, preserving correlations between expressions that share random choices.

  • Construct numeric vectors and matrices with RealMatrix declarations, such as fixed RealMatrix m = [1, 2; 3, 4];. Matrix support includes indexing, scalar conversion, arithmetic, transpose, constructors, stacking, reductions, determinants, and inverses. Entries and dimensions may depend on finite random choices.

  • Comments use // or non-nesting /* ... */.

1.4.1 Declaration order and random-function domains🔗ℹ

Random functions are instantiated eagerly: when a declaration is evaluated, its body is evaluated once for every argument tuple formed from the objects currently declared in its parameter types. The resulting table is fixed for that function. Later object declarations do not extend it.

For example, both people below exist before Age is declared:

#lang roulette/example/blog

 

type Person;

distinct Person Alice, Bob;

random Integer Age(Person p) ~ UniformInt(20, 40);

 

query Age(Alice);                    // works

query Age(Bob);                      // works

query Age(Alice) == Age(Alice);       // always true

The declaration creates one random age for Alice and another for Bob. Repeated calls with the same person retrieve that person’s stored choice; calling the function does not draw another age.

In this separate example, Bob is declared too late for Age:

type Person;

distinct Person Alice;

random Integer Age(Person p) ~ UniformInt(20, 40);

distinct Person Bob;

 

query Age(Alice);                    // works

query Age(Bob);                      // runtime error: outside grounded domains

Bob belongs to Person, but the existing function table has no entry for him. A quantifier over Person can see Bob after his declaration; this does not create an Age(Bob) entry. Declare the complete object population before the random function when all of its members need entries:

type Person;

distinct Person Alice;

distinct Person Bob;

random Integer Age(Person p) ~ UniformInt(20, 40);

query Age(Alice), Age(Bob);           // works

For multiple parameters, instantiation covers every ordered argument tuple:

type Person;

distinct Person Alice, Bob;

random Boolean Friends(Person p, Person q) ~ BooleanDistrib(0.5);

This creates entries for Friends(Alice, Alice), Friends(Alice, Bob), Friends(Bob, Alice), and Friends(Bob, Bob). Declaring Charlie afterward creates no additional entries in this table. An empty parameter domain produces no entries.

These rules apply to random declarations using either ~ or =. Types, objects, and parent functions used by the eagerly evaluated body must already be available. A zero-parameter random declaration evaluates its body once and stores a single value. Fixed functions are ordinary functions and do not create a table over the object population when declared.

1.4.1.1 Shared and independent random choices🔗ℹ

A stored random value represents all of its possible outcomes during inference. Reusing it preserves correlation; it does not select one outcome for the whole computation:

random Integer X ~ Bernoulli(0.5);

random Integer Y ~ Bernoulli(0.5);

query X + X;     // 0 or 2, each with probability 0.5

query X + Y;     // 0: 0.25, 1: 0.5, 2: 0.25

Both occurrences of X refer to the same choice, so X + X cannot equal 1. The second declaration creates an independent choice; X + Y can equal 1 in either of two ways.

1.4.2 Sequential and joint queries🔗ℹ

A program may contain multiple query statements. Each statement requests one result: either a usual single-expression marginal distribution or a joint distribution over comma-separated expressions. Both kinds execute sequentially.

1.4.2.1 Usual sequential queries🔗ℹ

Each query uses declarations and observations evaluated before its statement. Later observations do not change an earlier result. Running a BLOG module prints every query result in source order:

#lang roulette/example/blog

 

random Integer X ~ UniformInt(0, 1);

query X;             // 0 or 1, each with probability 1/2

obs X = 1;

query X;             // 1 with probability 1

query X + X;         // 2 with probability 1

Queries reuse the same model allocations; they do not redraw random constants or grounded random functions. Declarations remain subject to the existing loading order and grounding rules.

1.4.2.2 Multiple separate queries versus one joint query🔗ℹ

Consider two expressions sharing one random variable:

random Integer X ~ UniformInt(0, 1);

query X;             // First result:  0 or 1, each with probability 1/2.

query X + X;         // Second result: 0 or 2, each with probability 1/2.

These are two separate marginal distributions. They reuse the same X, but the results do not explicitly list which pairs can occur together. Multiplying their marginal probabilities would incorrectly assume independence: for example, the pair (0, 2) is impossible even though each component appears in its respective marginal.

To request that relationship explicitly, separate the expressions with commas in one joint-query statement:

random Integer X ~ UniformInt(0, 1);

query X, X + X;

// Joint outcomes: (0, 0) and (1, 2), each with probability 1/2.

Two independent variables instead produce all four pairs:

random Integer X ~ UniformInt(0, 1);

random Integer Y ~ UniformInt(0, 1);

query X, Y;

// (0, 0), (0, 1), (1, 0), (1, 1), each with probability 1/4.

Observations also affect subsequent joint queries. For example, obs X = 1; followed by query X, X + X; has only the outcome (1, 2). An observation placed between two separate queries affects only the later query; an observation before a joint query conditions the entire joint tuple. No observation can occur between the comma-separated expressions of one query statement. Empty joint components and trailing commas are syntax errors.

1.4.3 Lists and matrices🔗ℹ

Square brackets construct lists. These two expressions are equivalent:

[[1, 2, 3], [4, 5, 6]]

[1, 2, 3; 4, 5, 6]

The semicolon form is shorthand for a list of rows. Lists may be empty, nested, ragged, or contain nonnumeric values. Shorthand rows must be nonempty; write empty rows explicitly, as in [[], []].

A RealMatrix return annotation converts a list to a numeric matrix:

fixed RealMatrix row = [10, 20, 30];

fixed RealMatrix column = [10; 20; 30];

fixed RealMatrix table = [10, 20, 30; 40, 50, 60];

A flat list becomes a row vector, and nested lists become matrix rows. Conversion requires rectangular data with real numeric cells. Boolean cells, mixed rows and scalars, and nesting deeper than two levels are rejected. Existing matrices pass through unchanged. Exact integers and rationals remain exact; the constructor does not coerce every cell to floating point.

The empty list becomes a 0-by-0 matrix. Explicit empty rows retain their dimensions: [[], []] becomes a 2-by-0 matrix. Matrix constructors also accept zero dimensions.

1.4.3.1 When a list becomes a matrix🔗ℹ

The RealMatrix annotation tells a declaration to convert its result into a matrix. Brackets alone create a list. For fixed declarations:

fixed RealMatrix A = [1, 2];

fixed RealMatrix Pair(Integer x) = [x, x];

query Pair(3);                      // row matrix [3, 3]

Defining A evaluates [1, 2], converts that list into a row matrix, and stores it once. Calling Pair(3) evaluates [3, 3] and converts the result before returning it. A fixed function performs this evaluation and conversion on each call.

Random declarations convert their results too, but ~ and = produce those results in different ways:

random Integer X ~ UniformInt(0, 1);

random RealMatrix Draw ~ Categorical({[1, 2] -> 0.5, [3, 4] -> 0.5});

random RealMatrix FromX = [X, X];

query Draw;                         // matrix [1, 2] or [3, 4], equally likely

query FromX;                        // matrix [0, 0] or [1, 1], equally likely

The ~ declaration draws from a distribution of lists, then converts the result to a matrix. The = declaration computes a list from the existing X, then converts it. Both entries of FromX share that same choice; this declaration introduces no independent draw. These zero-parameter random declarations store their results once.

A random function stores one converted result for each combination of declared object arguments:

type Person;

distinct Person Alice, Bob;

random RealMatrix M(Person p) ~ Categorical({[1, 2] -> 0.5, [3, 4] -> 0.5});

query M(Alice) == M(Alice);          // always true

query M(Alice) == M(Bob);            // true or false, each with probability 0.5

When M is declared, Alice and Bob each get an independent matrix-valued choice. Each result is converted and stored at that time. Repeated calls to M(Alice) retrieve Alice’s stored choice; they do not draw or convert again.

Outside a RealMatrix declaration, a list stays a list. Equality compares the value types as well as their contents; it does not insert a conversion:

fixed RealMatrix m = [1, 2];

query m == [1, 2];                  // false: a matrix compared with a list

fixed RealMatrix n = [1, 2];

query m == n;                       // true: matrices with equal contents

1.4.3.2 Indexing and scalar conversion🔗ℹ

Indices are exact, zero-based integers. Families return objects and lists return stored elements. A matrix with multiple rows and columns returns a row matrix; indexing a row or column vector returns a 1-by-1 matrix.

query [[10, 20], [30, 40]][1][0];     // scalar 30

fixed RealMatrix m = [10, 20, 30; 40, 50, 60];

query m[1];                         // matrix [40, 50, 60]

query m[1][2];                      // singleton matrix [60]

query toReal(m[1][2]);               // scalar real 60.0

query transpose(m)[1];              // matrix [20, 50]

Indexing binds tightly and supports calls and grouped expressions, such as (a + b)[i][j]. Invalid or out-of-bounds indices raise errors. toReal and toInt accept real or Boolean scalars and singleton matrices. They produce an inexact real or an exact integer truncated toward zero; Booleans become 1 or 0. Larger or empty matrices are rejected, and integer conversion rejects nonfinite numbers.

1.4.3.3 Arithmetic and the matrix library🔗ℹ

Matrix operands must be matrix values, supplied by RealMatrix declarations or matrix-producing functions. Raw list literals are not automatically converted at an arithmetic operator or library call.

  • a + b and a - b require identical matrix dimensions. Unary + preserves a matrix and unary - negates its cells.

  • a * b performs matrix multiplication, requiring the left column count to equal the right row count. It is not elementwise multiplication.

  • a + s, s + a, a - s, and s - a apply real scalar addition/subtraction to every matrix cell, preserving the shape. In particular, s - a computes s - cell for each cell; adding a scalar does not mean adding a scaled identity matrix.

  • s * a and a * s scale a matrix by a real scalar. a / s divides each cell by a nonzero scalar. Matrix divisors remain unsupported.

  • eye(n), zeros(rows, columns), and ones(rows, columns) construct identity, zero-filled, and one-filled matrices. Dimensions must be nonnegative exact integers.

  • diag(column) creates a diagonal matrix from a column vector. repmat(m, rows, columns) tiles a complete matrix vertically and horizontally using nonnegative exact integer repetition counts.

  • hstack(...) joins matrices with matching row counts. vstack(...) joins matrices with matching column counts. Both require at least one argument and treat real scalars as 1-by-1 matrices, allowing compatible mixtures of scalars and matrices.

  • sum(m) returns the column sums as a row matrix. trace(m) returns the diagonal sum of a square matrix.

  • abs(m) and exp(m) apply elementwise and also accept real scalar inputs.

  • det(m) and inv(m) require square matrices with finite real entries. A singular matrix has determinant zero; its inverse raises an error. The 0-by-0 matrix has determinant 1, trace 0, and an empty inverse.

fixed RealMatrix a = [1, 2; 3, 4];

query a + a;                        // [2, 4; 6, 8]

query a + 10;                       // [11, 12; 13, 14]

query 10 - a;                       // [9, 8; 7, 6]

query a / 2;                        // exact entries 1/2, 1, 3/2, 2

query a * a;                        // [7, 10; 15, 22]

query sum(a);                       // row matrix [4, 6]

query det(a);                       // scalar -2

query inv(a);                       // [-2, 1; 3/2, -1/2]

query inv(a) * a == eye(2);          // true with these exact inputs

Other library calls construct and transform values:

query hstack(eye(2), zeros(2, 1));    // [1, 0, 0; 0, 1, 0]

query vstack(ones(1, 2), zeros(1, 2)); // [1, 1; 0, 0]

fixed RealMatrix column = [2; 3];

query diag(column);                 // [2, 0; 0, 3]

query repmat(column, 1, 2);          // [2, 2; 3, 3]

query abs(-3);                      // 3

query exp(0);                       // 1

Inexact arithmetic has ordinary floating-point rounding. Use numerical tolerances when comparing floating-point results from outside BLOG; exact matrix equality is appropriate for the exact example above.

1.4.3.4 Random entries and dimensions🔗ℹ

Finite random values may determine indices, matrix entries, and dimensions. Repeated references preserve the same underlying random choices:

random Integer x ~ UniformInt(0, 1);

random RealMatrix a = [x, x];

query a;                            // [0, 0] or [1, 1], each with probability 1/2

The cells share x, so [0, 1] and [1, 0] cannot occur. Dimensions can also depend on a shared random choice:

random Integer n ~ UniformInt(1, 2);

query eye(n) * ones(n, 1) == ones(n, 1); // always true

Shape checks consider correlated dimensions together, so the last expression does not pair eye(1) with ones(2, 1). Invalid reachable alternatives raise errors rather than disappearing from a distribution; see (part "blog-symbolic-validation") for the validation rules.

Routine arithmetic retains symbolic cells. Determinant and inverse enumerate finite concrete matrix alternatives before pivoted Gaussian elimination; these operations can be expensive with many independent random entries.

1.4.4 Current limitations🔗ℹ

  • Object populations are fixed and finite. Number statements for unknown populations and origin functions are not supported. Random-function arguments must range over declared object types. Built-in domains such as Integer are not supported as random-function argument domains.

  • Random functions are eagerly instantiated over the objects declared so far. Objects and parent random functions must precede their dependents. Objects declared later are not added to an existing random function’s domain. RealMatrix return annotations are checked and converted; other type annotations are not fully checked.

  • Sets and set comprehensions, higher-dimensional numeric arrays, strings, characters, and timestep literals are not supported. Numeric matrices use RealMatrix; no separate IntegerMatrix type is provided. Distributions other than the four listed above are not provided. Multivariate Gaussian sampling is not implemented. Matrix-valued categorical distributions support finite vector outcomes; matrix support does not provide continuous Gaussian distributions.

1.4.5 Implementation notes🔗ℹ

The following Racket forms explain the implementation in "roulette/example/blog.rkt"; they are not BLOG source syntax. Internal helpers are not part of the public language API. The test-support submodule exposes selected constructors for testing.

1.4.5.1 Parsing and normalized expressions🔗ℹ

blog-parse accepts a source name and an input port containing raw BLOG text, without a #lang line. It returns declaration and expression datums; parsing does not evaluate them:

(blog-parse 'example.blog

            (open-input-string "fixed RealMatrix m = [1, 2; 3, 4];"))

;; '((fixed RealMatrix m ()

;;          (blog-list (blog-list 1 2) (blog-list 3 4))))

The empty parameter list marks a constant. Row shorthand has already become nested blog-list calls; matrix conversion happens when the declaration is evaluated. Other representative translations are:

BLOG source

  

Parsed expression

42

  

42

true

  

#t

f(1, 2)

  

(call f 1 2)

(a + b)

  

(+ a b)

a[i][j]

  

(index (index a i) j)

Atoms include literals, names, calls, and parenthesized expressions. A postfix expression starts with an atom and may add index suffixes, associating to the left. Parentheses control grouping and disappear from the result. Parser actions such as $1 and $2 select matched grammar components; for a parenthesized expression, $2 selects its contents. Routing these forms through the postfix rule avoids duplicate grammar alternatives.

1.4.5.2 Matrix representation🔗ℹ

BLOG lists use blog-list-value; matrices use blog-matrix-value, with explicit row and column counts and an immutable list of cells in row order. Constructor notation below shows those fields:

(make-blog-matrix (blog-list 10 20))

;; (blog-matrix-value 1 2 '(10 20))

 

(make-blog-matrix (blog-list (blog-list 1 2) (blog-list 3 4)))

;; (blog-matrix-value 2 2 '(1 2 3 4))

 

(make-blog-matrix (blog-list))

;; (blog-matrix-value 0 0 '())

 

(make-blog-matrix (blog-list (blog-list) (blog-list)))

;; (blog-matrix-value 2 0 '())

Converting an existing matrix returns that same value. Numeric cells keep their exactness: for example, a cell containing 1/3 stays rational and 2.5 stays inexact. The shape and cell restrictions are described in Lists and matrices. The constructor additionally requires a tagged BLOG list or an existing matrix; an ordinary Racket list such as ’(1 2) and a standalone scalar are invalid inputs.

1.4.5.3 Declaration expansion and result conversion🔗ℹ

The internal blog-result-warpper macro inserts conversion for the RealMatrix annotation:

(define-syntax blog-result-warpper

  (syntax-parser

    [(_ (~datum RealMatrix) body:expr)

     #'(make-blog-matrix body)]

    [(_ result-type:id body:expr)

     #'body]))

The first rule matches that specific type name; the second accepts other type identifiers and leaves the body unchanged. Thus (blog-result-warpper Boolean 42) still evaluates to 42: annotations other than RealMatrix are not checked by this wrapper.

A fixed matrix constant passes through these expansion stages:

(fixed RealMatrix m () (blog-list 1 2))

;; expands to:

(define m (blog-result-warpper RealMatrix (blog-list 1 2)))

;; then to:

(define m (make-blog-matrix (blog-list 1 2)))

Conversion runs once for a fixed constant and on each call to a fixed function. For a random declaration, the outer random macro prepares the body: ~ adds draw-distribution, while = uses the dependency expression directly. It then applies the result wrapper and delegates storage to define-random:

(define-syntax define-random

  (syntax-parser

    [(_ name:id () body:expr)

     #'(define name body)]

    [(_ name:id ((arg-type:id arg:id) ...+) body:expr)

     #'(define name

         (make-random-function 'name (list arg-type ...)

                               (lambda (arg ...) body)))]))

The zero-parameter rule stores the prepared result directly. The parameterized rule passes the type domains and body procedure to make-random-function. Here, ...+ requires at least one parameter pair; the other ellipses collect the matched types and names. For example:

(define-random X () (draw-distribution (Bernoulli 0.5)))

;; expands to:

(define X (draw-distribution (Bernoulli 0.5)))

 

(define-random Healthy ((Person p))

  (draw-distribution (BooleanDistrib 0.8)))

;; expands to:

(define Healthy

  (make-random-function 'Healthy (list Person)

    (lambda (p) (draw-distribution (BooleanDistrib 0.8)))))

The resulting function looks up stored values; it does not evaluate the procedure again on every call. Its eager grounding and declaration-order rules are described in Declaration order and random-function domains.

1.5 Bentham🔗ℹ

 #lang roulette/example/bentham package: roulette

Bentham is a more restrictive version of Disrupt with support for calculating expected utility.
> (define x (flip 1/2))
> (define y (flip 1/2))
> (when x (reward! 99))
> (expected-utility (not (and x y)))

33

If x holds, then the program accumulates 99 in utility via the reward! procedure. The query function returns the expected utility of the program conditional on (not (and x y)). From earlier, we know that the conditional probability of x given this expression is 1/3. Therefore, the expected utility is 33.

procedure

(flip p) → boolean?

  p : (real-in 0 1)

procedure

(observe! e) → void?

  e : boolean?
These procedures have the same meaning as they do in Disrupt.

procedure

(reward! e) → void?

  e : number?
Adds e to the amount of utility accumulated by the current program execution.

procedure

(expected-utility e) → number?

  e : any/c
Returns the expected utility given e.