codecamp

hack形状案例

任意类型

形状类型可以具有任意类型的零个或多个字段。

<?hh

namespace Hack\UserDocumentation\Shapes\Examples\Examples\Arbitrary;

type Complex = shape('real' => float, 'imag' => float);
type Hits = shape('id' => string, 'url' => string, 'count' => int);
type Math = shape('n1' => array<num>,
                  'n2' => (function (array<num>): float));
type APoint<T> = shape('x' => T, 'y' => T);

function take_complex(Complex $c): void {
  echo $c['real'] . ' + ' . $c['imag'] . 'i' . PHP_EOL;
}

function get_hits(Hits $h): void {
  echo 'User with id: ' . $h['id'] . ' has hit ' . $h['url'] . ' ' .
       $h['count'] . ' times.' . PHP_EOL;
}

function do_math(Math $m): void {
  var_dump($m['n2']($m['n1']));
}

function create_point<T>(APoint<T> $p): void {
  var_dump($p);
}

function run(): void {
  take_complex(shape('real' => 4.0, 'imag' => 2.0));
  get_hits(shape('id' => 'Rex', 'url' => 'http://example.com', 'count' => 10));
  do_math(shape('n1' => array(2, 4.0, 2, 999, 1000.23),
    'n2' => function (array<num> $nums): float {
      return array_sum(array_filter($nums, $x ==> is_float($x)));
     }
  ));
  create_point(shape('x' => true, 'y' => false));
}

run();

Output

4 + 2i
User with id: Rex has hit http://example.com 10 times.
float(1004.23)
array(2) {
  ["x"]=>
  bool(true)
  ["y"]=>
  bool(false)
}
hack形状子类型化
hack元组介绍
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }