Welcome to Day 16 of the Perl 6 One-Liner Advent Calendar! Today, we’ll solve a simple problem and will find the distance between two points on a surface.
Here’s an illustration to help to formulate the task. Our goal is to find the distance between the points A and B.
To make the answer more transparent and easy to check, I chose the line AB so that it is a hypotenuse of a right triangle with sides 3 and 4. The length of the third side will be 5 in this case.
So, here’s the solution:
say abs(5.5+2i - (1.5+5i))
The code uses complex numbers, and as soon as you move to a complex plane, you gain from the fact that the distance between two points on the surface equals to the absolute result of subtraction of these two numbers from one another.
One of the points, in this case, is the point 5.5+2i on a complex plane, and the second point is 1.5+5i. In Perl 6, you write complex numbers as you do in mathematics.
Without the built-in support of complex numbers, you would have to use Pythagorean theorem explicitly:
say sqrt((5.5 - 1.5)² + (2 - 5)²)
Homework. Modify Rakudo’s grammar to allow the following code:
say √((5.5 - 1.5)² + (2 - 5)²)
And that’s all for today. Come again tomorrow to read about another Perl 6 one-liner or two!