Hack Language

 

2015 April 13th

Andy Truong

Twitter: thehongtt

Why Hack?

  • Static typing
  • Elegant syntax
  • PHP compatible

New features

Lamda

<?php
$n = 20;
$inc = function($x) use ($n) { return $x + $n; }
$inc(10); // 30
<?hh
$n = 20;
$inc = $a ==> $a + $n;
$inc(10); // 30

HTML Rendering

<?hh

function box(
    string $title, 
    string $body): :div {
        return 
            <div>
                <h2>{$title}</h2>
                {$body}
            </div>
}

Short class constructor

<?php

class Point {
  public function __construct(
     private float $x, 
     private float $y) {}

  public function getX(): float { return $this->x; }
  public function getY(): float { return $this->y; }
}

Safe properties

<?hh

new Point();     // error
new Point(0, 0); // OK

Trait requirements

<?hh

class DrupalEntity { 
    public function getUuid(): string {
        return '…';
    }
}

trait CacheFlusher {
    require extends DrupalEntity;
    
    public function getCacheId(): string {
        return 'cacheId:' . $this->getUuid();
    }
}

More data types

string/int/float/enum/…

Enum

<?hh

enum gender = {
    male = 1;
    female = 0;
}

function print_gender(gender $gender): string {
    return 'Your are :' 
        . $gender ? 'male' : 'female'
    ;
}

Vector

<?hh
$vector = Vector {1, 2, 3};
$sum = 0;
foreach ($vector as $val) {
    $sum += $val;
}
var_dump($sum);

Map

<?hh

$m = Map {'a' => 1, 'b' => 2};
function foo(Map<string, int> $c): void {
    // Do foo things!
}

Turple

<?hh

function my_first_pair((int, bool) $pair): bool
{
  list($_, $result) = $pair;
  return $result;
}

Shape

<?hh

type point = shape(
    'x' => float,
    'y' => float,
);

function dummy_point(?float $x, ?float $y): point {
  return shape(
    'x' => $x === null ? 0 : $x,
    'y' => $y === null ? 0 : $y
  );
}

And much more

at hacklang.org

Hack Language

By Andy Truong

Hack Language

  • 1,524