tobyink / p5-type-tiny

Perl 5 distribution Type-Tiny; see homepage for downloads and documentation.
https://typetiny.toby.ink/
54 stars 48 forks source link

slurpy parameter cannot be optional #140

Open XSven opened 1 year ago

XSven commented 1 year ago

I have a type definition that is a non-empty(!) array reference. This type definition is used at several places. At one place I want to use this type definition in a slurpy optional context. This does not work. I am using the slighly modified example taken from the section slurpy Bool

sub add_nums {
  state $sig = signature(
    positional => [
      Num,
      ArrayRef[Num,1], { optional => !!1, slurpy => !!1 }
    ],
  );
  my ( $first_num, $other_nums ) = $sig->( @_ );

  my $sum = $first_num;
  $sum += $_ for @$other_nums;

  return $sum;
}

print add_nums( 1 ), "\n";

I am getting the failure

Failed to compile source because: syntax error at parameter validation for 'main::add_nums' line 15, near ";

        # Parameter $SLURPY (type: Slurpy[ArrayRef[Num,1]])
         >=" at add_nums.pl line 9.
tobyink commented 1 year ago

While I agree that compile error is definitely not what should happen, I also don't think it's clear what the "correct" behaviour would be either.

A slurpy parameter is intended to hold "all the rest of the arguments" and will always be some kind of arrayref or hashref. If there's no "rest of the arguments", then that just ends up being an empty arrayref or hashref. I don't think it makes a lot of sense to talk about a slurpy parameter being required or optional.

My instinct is that Type::Params should just ignore optional entirely on slurpy parameters.

XSven commented 1 year ago

Fine but then the type constraint check should be skipped because my type refers to a non-empty array reference OR we need a type constraint that represents an empty array reference that I could use for a union. My gut feeling tells me that the first approach should be preferred: Detailed type checking beyond basic ArrayRef or HashRef type checking should only be done, if something can be slurped.

tobyink commented 1 year ago

That would break backwards compatibility with versions of Type::Params before compile_named was introduced. Back then the only way to do named parameters was:

my $check = compile( slurpy Dict[
  name   => Str, # required
  age    => Optional[Int],
] );

The slurpy needs to be checked; otherwise the requiredness of name won't be enforced.

Hmmm. I guess in the case of an optional slurpy parameter, then optional could be treated as a signal to "always allow the empty arrayref/hashref to pass".