3

So Hacklang is out with a new, fancy type system, where a nullable variable has to be checked before it can be used. What I wonder is, can you achieve something like linear types, statically forcing an order of function calls, the common example being open a file before reading it? In pseudo-code:

$file_handler = get_file_handler("myfile");
$file_handler->open();
$string = $file_handler->read();

Now, $file_handler->read() without open() would rather than throwing a runtime exception, just not compile:

$file_handler = get_file_handler("myfile");
$string = $file_handler->read(); /* Won't compile, must run open() first */

Doable?

(OK, maybe bad example for PHP/Hacklang, since it is not this lowlevel, but you get the idea.)

4

1 回答 1

6

Hack 目前没有对线性类型的任何原生支持。对于您询问的特定情况,不透明类型别名在包装类中可能很有用:(危险,直接输入浏览器的代码,可能有小错误,但应该说明想法)

<?hh

newtype closedfile = resource;
newtype openfile = resource;

function get_file_handler(string $filename): closedfile {
  return some_wrapped_function($filename);
}

function open_file_handler(closedfile $file): openfile {
  $file->open();
  return $file;
}

function read(openfile $file): string {
  return $file->read();
}

根据您的应用程序,这样做可能是不可能的,甚至是一个好主意,但它是最接近我们目前所拥有的。

也就是说,如果您正在设计 API 而不是使用现有的东西,那么最好将其设计为没有尚未打开的文件之类的东西,从而消除此类错误从一开始就不需要任何类型系统杂技。(基本上,至少在我看来,这是一个 API 设计问题,而不是类型系统问题!即使您可以使用类型系统静态地使无效代码成为错误,API 的使用者甚至可以编写代码并认为它​​可能有意义是 API 的一个缺陷。)

于 2014-05-10T21:29:31.560 回答