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 | |
> (define first-coin (flip 0.5)) > first-coin
┌─────┬───────────┐
│Value│Probability│
├─────┼───────────┤
│#t │0.5 │
│#f │0.5 │
└─────┴───────────┘
> (define second-coin (flip 0.5)) > (define both-heads (and first-coin second-coin)) > both-heads
┌─────┬───────────┐
│Value│Probability│
├─────┼───────────┤
│#t │0.25 │
│#f │0.75 │
└─────┴───────────┘
> (observe! (not both-heads)) > first-coin
┌─────┬──────────────────┐
│Value│Probability │
├─────┼──────────────────┤
│#t │0.3333333333333333│
│#f │0.6666666666666666│
└─────┴──────────────────┘
> (if (flip 1/2) 'a 'b)
┌─────┬───────────┐
│Value│Probability│
├─────┼───────────┤
│'b │0.5 │
│'a │0.5 │
└─────┴───────────┘
> (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 │
└─────┴───────────┘
syntax
(with-observe body ...+)
> (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])
syntax
(with-sample iter body ...+)
> (with-sample 100 (sample (flip 1/3)))
┌─────┬──────────────────┐
│Value│Probability │
├─────┼──────────────────┤
│#t │0.2800000000000001│
│#f │0.72 │
└─────┴──────────────────┘
> (define (expectation v) (for/sum ([(val prob) (in-pmf (query v))]) (* val prob))) > (expectation (if (flip 1/2) 5 10)) 7.5