# ðŸ“˜ Working with polar coordinates in Perl 6

Convert the Cartesian coordinates to polar and backward.

Polar coordinates are a convenient way of representing points on a surface with the two values: distance from the centre of coordinates and the angle between the vector and the pole axis.

The conversion formulae between the Cartesian and polar systems,which is valid for positiveÂ x andÂ y, are the following:

These expressions can be implemented as-is in the Perl 6 code:

`sub polar-to-cartesian(\$r, \$Ï†) {    \$r * cos(\$Ï†), \$r * sin(\$Ï†)}sub cartesian-to-polar(\$x, \$y) {    sqrt(\$xÂ² + \$yÂ²), atan(\$y / \$x)}`

The functions return lists of either polar or Cartesian coordinates. Because of the simplicity of implementation, it is fine to omit the returnkeyword and the semicolon at the end of the line.

Call the conversion functions with some positive numbers and check that the initial coordinates are restored after the second conversion:

`say cartesian-to-polar(1, 2);say polar-to-cartesian(2.236068, 1.107149);`

For the negativeÂ x andÂ y, the Cartesian-to-polar conversion is a bit more complicated. Depending on the quadrant of the point, theÂ Ï† Â value is bigger or smaller byÂ . WhenÂ xis zero, it is eitherÂ â€“pi/2Â orÂ pi/2.

All these variants can be implemented in Perl 6 by using multi-subroutines with the whereclause, as demonstrated below:

```sub cartesian-to-polar(\$x, \$y) {
Â Â Â Â sqrt(\$xÂ² + \$yÂ²), cartesian-to-Ï†(\$x, \$y)
}

multi sub cartesian-to-Ï†(\$x, \$y where {\$x > 0}) {
Â Â Â Â atan(\$y / \$x)Â
}

multi sub cartesian-to-Ï†(\$x, \$y where {\$x < 0 && \$y â‰¥ 0}) {
Â Â Â Â atan(\$y / \$x) + Ï€
}

multi sub cartesian-to-Ï†(\$x, \$y where {\$x < 0 && \$y < 0}) {
Â Â Â Â atan(\$y / \$x) â€“ Ï€
}

multi sub cartesian-to-Ï†(\$x, \$y where {\$x == 0 && \$y > 0}) {
Â Â Â Â Ï€ / 2
}

multi sub cartesian-to-Ï†(\$x, \$y where {\$x == 0 && \$y < 0}) {
Â Â Â Â -Ï€ / 2
}

multi sub cartesian-to-Ï†(\$x, \$y where {\$x == 0 && \$y == 0}) {
Â Â Â Â Nil
}```