Division by zero in Raku

Division by zero in Raku is one of my favourite topics. Let me demonstrate a couple of approaches that can be used in solving Task 1 of the Perl Weekly Challenge 31.

The task is to write a function that checks the division by zero without explicitly comparing the denominator with zero.

Division by zero in Raku is one of my favourite topics. Let me demonstrate a couple of approaches that can be used in solving Task 1 of the Perl Weekly Challenge 31.

The task is to write a function that checks division by zero without explicitly comparing the denominator with zero.

Let me offer a couple of solutions.

1

for -3 .. 3 -> $n {
    my $m = 42 / $n;
    print "42 / $n = ";
    say $m == Inf ?? 'Division by 0 detected' !! $m;
}

The power of Raku is that you actually can divide by zero, but just make sure you use the result carefully. In this program, we check if the result is infinitive, and if so, print a message instead of a value:

$ raku ch-1.raku 
42 / -3 = -14
42 / -2 = -21
42 / -1 = -42
42 / 0 = Division by 0 detected
42 / 1 = 42
42 / 2 = 21
42 / 3 = 14

2

An actual error will be thrown if we will try to use the result of division, for example, if we print it. In this case, you need to catch the error:

for -3 .. 3 -> $n {
    print "42 / $n = ";
    try {
        say 42 / $n;

        CATCH {
            default {
                say 'Division by 0 detected';
            }
        }
    }
}

This program produces the same output.

GitHub repository
Navigation to the Raku challenges post series

Leave a Reply

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