Type Aliases: Examples

Complex Number

You can use type aliases to represent a complex number.

<?hh // strict

// complex.inc.php - Complex number implementation file

namespace Hack\UserDocumentation\TypeAliases\Examples\Examples\ComplexNumber;

newtype Complex = shape('real' => float, 'imag' => float);

function createComplex(float $real = 0.0, float $imag = 0.0): Complex {
  return shape('real' => $real, 'imag' => $imag);
}

function getI(): Complex {
  return shape('real' => 0.0, 'imag' => 1.0);
}

function getReal(Complex $z): float {
  return $z['real'];
}

function getImag(Complex $z): float {
  return $z['imag'];
}

function setReal(Complex $z, float $real = 0.0): Complex {
  $z['real'] = $real;
  return $z;
}

function setImag(Complex $z, float $imag = 0.0): Complex {
  $z['imag'] = $imag;
  return $z;
}

function add(Complex $z1, Complex $z2): Complex {
  return shape('real' => $z1['real'] + $z2['real'],
               'imag' => $z1['imag'] + $z2['imag']);
}

function subtract(Complex $z1, Complex $z2): Complex {
  return shape('real' => $z1['real'] - $z2['real'],
               'imag' => $z1['imag'] - $z2['imag']);
}

function toString(Complex $z): string {
  if ($z['imag'] <= 0.0) {
    return "(" . $z['real'] . " - " . (-$z['imag']) . "i)";
  } else if (1.0/$z['imag'] == -INF) {
    return "(" . $z['real'] . " - " . 0.0 . "i)";
  } else {
    return "(" . $z['real'] . " + " . (+$z['imag']) . "i)";
  }
}
<?hh

// use-complex.php

namespace Hack\UserDocumentation\TypeAliases\Examples\Examples\ComplexNumber;

function run(): void {
  $z1 = getI();
  echo "\$z1 contains " . toString($z1) ."\n";

  $z2 = createComplex();
  echo "\$z2 contains " . toString($z2) ."\n";

  $z3 = createComplex(10.0);
  echo "\$z3 contains " . toString($z3) ."\n";

  $z4 = createComplex(-4.0, 3.5);
  echo "\$z4 contains " . toString($z4) ."\n";

  echo "\$z4's real part is " . getReal($z4) ."\n";
  echo "\$z4's imaginary part is " . getImag($z4) ."\n";

  $z2 = setReal($z2, -3.0);
  $z2 = setImag($z2, 2.67);
  echo "\$z2 contains " . toString($z2) ."\n";

  $z5 = add($z2, $z4);
  echo "\$z5 contains \$z2 + \$z4: " . toString($z5) ."\n";

  $z6 = subtract($z2, $z4);
  echo "\$z6 contains \$z2 - \$z4: " . toString($z6) ."\n";
}

run();
Output
$z1 contains (0 + 1i)
$z2 contains (0 - 0i)
$z3 contains (10 - 0i)
$z4 contains (-4 + 3.5i)
$z4's real part is -4
$z4's imaginary part is 3.5
$z2 contains (-3 + 2.67i)
$z5 contains $z2 + $z4: (-7 + 6.17i)
$z6 contains $z2 - $z4: (1 - 0.83i)