Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Perl6 check the array length after append?

Tags:

types

raku

I've defined a new type Tuple as follows:

subset Tuple of Array where { .elems == 2 && .[0] < .[1] };
my Tuple $t = [1, 2];
say $t;  # [1 2] So far, so good.

I can't initialize it with shorter or longer array or with [2, 1], as expected. But, I can append to it:

$t.append(3);
say $t;  # [1 2 3] Ouch!

How's that possible?

like image 559
choroba Avatar asked Aug 15 '16 00:08

choroba


People also ask

How do you find the length of an array?

Using sizeof() One way​ to find the length of an array is to divide the size of the array by the size of each element (in bytes).

Is there a way to increase the size of an array after its declaration?

An ArrayList can only hold object values. You must decide the size of the array when it is constructed. You can't change the size of the array after it's constructed. However, you can change the number of elements in an ArrayList whenever you want.

Does .length work on arrays?

The length() method returns the number of characters present in the string. 1. The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not for arrays.

Do you have to declare the length of an array?

In a word - yes. You must specify the size of an array when you initialize it.


1 Answers

my Tuple $t creates a $t variable such that any (re)assignment or (re)binding to it must (re)pass the Tuple type check.

= [1, 2] assigns a reference to an Array object. The Tuple type check is applied (and passes).

$t.append(3) modifies the contents of the Array object held in $t but does not reassign or rebind $t so there's no type check.

Mutating-method-call syntax -- $t.=append(3) instead of $t.append(3) -- will trigger the type check on $t.

There is specific syntax for a bounds-checked array (my @array[2] etc.) but I'm guessing that's not the point of your question.

like image 69
raiph Avatar answered Dec 06 '22 09:12

raiph