我可以内省变量以直接发现它声明的子集吗?

Can I introspect a variable to directly discover what subset it was declared with?

有没有一种方法可以内省变量以直接找出它声明的子集?在这里我创建了一个子集,但内省指向它的基本类型:

> subset Prime of Int where .is-prime
(Prime)
> my Prime $x = 23
23
> $x.WHICH
Int|23

我知道它必须将信息存储在某处,因为如果我尝试重新分配一个与子集不匹配的值,它将失败:

> $x = 24
Type check failed in assignment to $x; expected Prime but got Int (24)
in block <unit> at <unknown file> line 1

我试着搜索代码,但我很快就进入了像 container.c and perl6_ops.c where the C code makes my eyes glaze over. I thought that X::TypeCheck::Assignment might help (see core/Exception.pm), but it's not clear to me where the expected value comes from. (see also this commit)

这样的文件

我觉得我遗漏了一些明显的东西。

我可以检查某物是否与一个子集匹配,但这并不能告诉我它是否是用特定子集声明的:

> my Int $y = 43;
43
> $y ~~ Prime;
True

我正在使用 Rakudo Star 2017.01


受到 Zoffix 在 a recent post 中使用子集的启发。

您存储在 $x 中的值是一个 Int。容器(您键入 Prime)是可以接受的,因为 PrimeInt.

的子类型

所以你感兴趣的不是容器中的值,而是容器的类型。为了获取容器,Perl 6 有 .VAR 方法。并且有一个 .of method 来获取类型:

$ 6 'subset Prime of Int where .is-prime; my Prime $x; dd $x.VAR.of'
Prime