Question

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.)

Était-ce utile?

La solution

Hack does not currently have any native support for linear types. For the particular case you're asking about, an opaque type alias might be useful in a wrapper class: (danger, code typed directly into browser, may have minor errors but should illustrate idea)

<?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();
}

Depending on your application, doing this may not be possible or even a good idea, but it's the closest to what we have right now.

That said, if you're designing the API as opposed to using something existing, it might be a good idea to just design it such that there isn't such a thing as a not-yet-opened file, eliminating this sort of error from the start without any type system acrobatics necessary. (Basically, in my opinion at least, this is an API design problem, not a type system problem! Even if you could use the type system to make invalid code an error statically, the fact that the consumer of the API could even write that code and think it's potentially meaningful is a deficiency in the API.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top