The Pearls of Raku, Issue 9: toss a coin; topic vs temporary variables

In this issue of the series, we are talking about two topics. The first is how to toss a coin using Raku. The second is how to avoid duplicated computations by setting the topic.

Welcome to the next issue of the Pearls in Raku.

Table of Contents

Toss a coin

This is probably the shortest way to toss a coin in Raku (or flip a coin if you wish):

say Bool.pick;

You get either False or True. That simple.

Alternatively, you can use roll:

say Bool.roll;

If you need to make more than one experiment, tell the number you need:

say Bool.roll(7);

The method returns a sequence of seven random Booleans in this case:

(False True True False False True False)

Setting a topic

Try solving the following simple task without using any variables:

Generate a random integer below 20 and print it if it was a prime number.

A typical solution would require a variable to keep the generated number:

my $n = 20.rand.Int;
say $n if $n.is-prime;

In Raku, you can set a topic and use it to do more than one action with it. For example, using given:

.is-prime && .say given 20.rand.Int;

The same effect is achieved via with or for:

.is-prime && .say for 20.rand.Int;
.is-prime && .say with 20.rand.Int;

In the above examples, we are calling methods directly on the topic variable but you are free to use the $_ variable explicitly.

Here’s another task:

In an array of random integers, find and print the maximum even number but only if it is bigger then 5, otherwise print 0.

So, let’s prepare the data first:

my @t = (^10).roll(5);
say @t;

A possible solution without using temporary variables could look like this:

say @t.grep(* %% 2).max > 5 ?? @t.grep(* %% 2).max !! 0;

Unfortunately, we compute the value twice here. Let’s avoid that by setting a topic:

with @t.grep(* %% 2).max {
    say $_ > 5 ?? $_ !! 0
}

Of course, a postfix form is also possible:

say $_ > 5 ?? $_ !! 0 with @t.grep(* %% 2).max;

Or:

say $_ > 5 ?? $_ !! 0 given @t.grep(* %% 2).max;

* * *

Find the code of this issue on GitHub and browse for more Raku Pearls.

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code