Rejection Sampling with Perl 6

Perl 6 provides a way to create lazy lists using the gather/take keywords. What I wanted to do was create an infinite list of samples from a known distribution of values. A simple way to sample from a known distribution is to do Rejection Sampling and doing this in Perl 6 is super easy.

sub sample(%distribution) {
  gather {
    loop {
      my $v = %distribution.pick;
      take $v.key if rand <= $v.value;

This function creates a Seq and you grab values from it in a lazy way. Here is a simple example assigning 100 samples from a distribution
to an array.

my %distribution = a=> 0.3, b=> 0.4, c=>0.1, d=>0.2;
my @samples = sample(%distribution)[0..^100];

Perl 6 is super fun. It has taken all the cool features from all the other languages and ignored the bad stuff. In this case, lazy lists from Haskell.

Read Seqs, Drugs, and Rock’n Roll to learn more about Sequences in Perl 6.

One thought on “Rejection Sampling with Perl 6

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s