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.
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.
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.
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.
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)
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
Predicate for PMFs.