develooper Front page | perl.perl5.porters | Postings from August 2018

Feature idea: allow for variable attributes in subroutine signatures

Thread Next
August 26, 2018 00:50
Feature idea: allow for variable attributes in subroutine signatures
Message ID:
Hello List,

apologies if that has been discussed before, in which case I politely
ask for pointers to such discussions to educate myself about the state
of affairs in that point.

Curtis "Ovid" Poe recently gave a talk in Glasgow in which he wished for
a gradual typing system in perl. IMHO, this could be done allowing for
variable attributes in subroutine signatures.


     use Attribute::Handlers;

     package Uint {
 	require Tie::Scalar;
 	@Uint::ISA = qw(Tie::StdScalar);
 	sub STORE {
 	    my ($p,$f,$l) = caller;
 	    $_[1] !~ /^[0-9]+\z/a
 		and die "not a positive integer in package $p file $f line $l, aborted";
 	    ${$_[0]} = $_[1];

     sub UNIVERSAL::Uint : ATTR(SCALAR) { tie ${$_[2]}, 'Uint' }

     sub fib {
 	my $nth : Uint = shift; # check for extra items in @_ missing
 	return $nth if $nth <= 1;
 	return fib( $nth - 1 ) + fib( $nth - 2 );

     say fib @ARGV;

Now, the fib() subroutine could - with the proposed extension - be
written like this, moving the checks into the signature (and obsoleting
them in the subroutines body):

     sub fib :prototype($) ($nth : Uint) {

which would allow for checking the lexicals of a signature at runtime.
(This is just a guess since I'm currently unaware of implementation
details of subroutine signature variables.)

Providing default attribute handling for defined types in perl's core
(say int, unsigned_int, string, not_null and such) would be of little
cost, while the proposed syntax still allows for user defined types.

As shown above, type checking can be done nicely with lexical attributes
but with a great performance loss due to the overhead of A:H and T:S -
well, at least in my example ;-)

This proposal would mean extending the built-in lowercase attributes in
a sensible way. Also, it would improve orthogonality wrt declaration of
lexicals overall, since that change could (should imho) be applied to
whatever declaration of attributes, which would mean we could constrain
a variable's content to a certain data type - optionally. Voilà, that
would be a gradual optional type system for perl.

What do you think?

I would like to try to implement that, but whilst having hacked some
perl core things for fun and experimentation, I'm quite a noob at it.

Hacking perly.y would be the first step and re-creating perly.{tab,c} I
guess, but then... any pointers are very welcome.

Best regards,

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                               /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About