๐ŸŽ„ 16/25. Distance between two points in Perl 6

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”

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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