Skip to content

Commit 56e386c

Browse files
committed
Some notes on nominal nature of array typing.
1 parent 9d3e034 commit 56e386c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

doc/Language/list.pod

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,30 @@ not bind an Array that has the wrong type to a typed C<@>-sigiled variable:
315315
my Int @b := Array[Int].new(1,2,3); # fine
316316
@b := Array.new(1,2,3); # error: Type check failed in binding
317317
318+
When working with typed arrays, it is important to remember that they are
319+
nominally typed. This means the declared type of an array is what matters.
320+
Given the following sub declaration:
321+
322+
sub mean(Int @a) {
323+
@a.sum / @a.elems
324+
}
325+
326+
Calls that pass an Array[Int] will be successful:
327+
328+
my Int @b = 1,3,5;
329+
say mean(@b); # @b is Array[Int]
330+
say mean(Array[Int].new(1,3,5)); # Anonymous Array[Int]
331+
say mean(my Int @ = 1,3,5); # Another anonymous Array[Int]
332+
333+
However, the following calls will all fail, due to passing an untyped array,
334+
even if the array just happens to contain Int values at the point it is
335+
passed:
336+
337+
my @c = 1,3,5;
338+
say mean(@c); # Fails, passing untyped Array
339+
say mean([1,3,5]); # Same
340+
say mean(Array.new(1,3,5)); # Same again
341+
318342
Note that in any given compiler, there may be fancy, under-the-hood, ways to
319343
bypass the type check on arrays, so when handling untrusted input, it can be
320344
good practice to perform additional type checks, where it matters:

0 commit comments

Comments
 (0)