On this page:
1.1 Disrupt
flip
query
observe!
with-observe
in-pmf
pmf?
8.17.0.3

1 Examples🔗ℹ

Roulette enables programmers to build languages that require the use of inference engines. This section gives an example of a language 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

(pmf | #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

(pmf | #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

(pmf | #t ↦ 0.333333 | #f ↦ 0.666667)

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)  boolean?

  p : (real-in 0 1)
Returns a Boolean where #t has probability p and #f has probability (- 1 p).
> (if (flip 1/2) 'a 'b)

(pmf | 'b ↦ 0.5 | 'a ↦ 0.5)

procedure

(query e)  pmf?

  e : any/c
Returns the probability mass function (PMF) associated with e. In other words, query performs top-level inference. See in-pmf for an example of how to use the result of this function.
> (query (flip 1/2))

(pmf | #t ↦ 0.5 | #f ↦ 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)

(pmf | #t ↦ 0.25 | #f ↦ 0.75)

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

(pmf | #t ↦ 0.5 | #f ↦ 0.5)

syntax

(with-observe body)

Delimits observations to the dynamic extent of body. After body has finished, any observations executed during body are forgotten.
> (define x (flip 1/2))
> (define y (flip 1/2))
> (with-observe
    (observe! x)
    (query (and x y)))

(pmf | #t ↦ 0.5 | #f ↦ 0.5)

> (query (and x y))

(pmf | #t ↦ 0.25 | #f ↦ 0.75)

procedure

(in-pmf e)  stream?

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

7.5

procedure

(pmf? e)  boolean?

  e : any/c
Predicate for PMFs.