develooper Front page | perl.perl6.language | Postings from June 2006

bind variable name to type

Daniel Hulme
June 22, 2006 07:12
bind variable name to type
Message ID:
Would it be useful to have a way of 'binding' a variable name to a given
type, in a given lexical scope, such that every time a variable with
that name is declared in that scope it gets to be of that type? What I'm
thinking of is a bit like how in Fortran variables called n are
automatically integers, and x is automatically real, and such, but off
by default and such that you can set it for any variable name.

My motivation behind this is that I'm currently writing C code where
every function declares a variable uErr, always holding an error code,
and most functions have variables called things like pUserHandle, always
holding a pointer to the same type of data structure. This feature would
allow me to write this code (if it were Perl 6) like

type $user UserHandle;
type $uErr ErrorCode;

sub renameUser($user, String $newName) returns ErrorCode {
  # $user is automatically of type UserHandle
  my $uErr; # $uErr is automatically of type ErrorCode
  $uErr = ERROR;
  return $uErr;

Yes, this kind of copper-plate code is really annoying, and to an
extent OO makes it much easier to write (by not having all your
functions take the same argument), but I'm sure we've all written code
like this once or twice. You could probably do this with a macro
containing a large given/when, but I would prefer an easy-to-read,
works-everywhere method.

This would give me the convenience of not having to type my types (if
you'll excuse the pun) but still allow static type-checking to detect
errors and reduce the overhead of variant types. Presumably trying to
declare a variable with a bound name to have a different type to the
bound one would be a compile-time error.

In shops where so-called Hungarian notation is in use (like my current
employer), it would make it much more useful, especially if the aliases
worked by regex rather than just with one name. That way, you could have
a 'coding style' project-wide module with things like

type /\$n/ Int;
type /\$d/ Real;
type /\$sz/ String;

and then have everyone

use Hungarian;

at the top of their files.  I'm not suggesting that these things be
encouraged, nor that the syntax should be the one I have used, but I can
see the feature being really useful in a range of circumstances. Any

"The  rules  of  programming  are  transitory;  only  Tao  is  eternal. 
 Therefore you  must contemplate Tao before you receive  enlightenment."
"How will I know when I have received enlightenment?"  asked the novice.
"Your program will then run correctly," replied the master.        Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About