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!
2 thoughts on “๐ 16/25. Distance between two points in Perl 6”