在 Perl 6 中将 .unique(:as ...) 与数字一起使用
Using .unique(:as ...) with numbers in Perl 6
在docs中解释了如何在调用.unique
之前标准化列表的元素:
The optional :as parameter allows you to normalize/canonicalize the
elements before unique-ing. The values are transformed for the
purposes of comparison, but it's still the original values that make
it to the result list.
并给出以下示例:
say <a A B b c b C>.unique(:as(&lc)) # OUTPUT: «(a B c)»
如果我想让一个有理数列表唯一,只比较它们的整数部分怎么办? :as
后括号内的Int
方法应该怎么调用?
my @a = <1.1 1.7 4.2 3.1 4.7 3.2>;
say @a.unique(:as(?????)) # OUTPUT: «(1.1 4.2 3.1)»
更新:
在@Håkon 的 的基础上,我找到了以下解决方案:
> say @a.unique(:as({$^a.Int}));
(1.1 4.2 3.1)
或
> say @a.unique(as => {$^a.Int});
(1.1 4.2 3.1)
没有$^a
可以吗?
UPD2:
是的,就在这里!
> say @a.unique(as => *.Int);
(1.1 4.2 3.1)
或
> say (3, -4, 7, -1, 1, 4, 2, -2, 0).unique(as => *²)
> (3 -4 7 -1 2 0)
或
> say @a.unique: :as(*.Int);
(1.1 4.2 3.1)
一种方法是将 anonymous 子例程传递给 unique
。例如:
my @a = <1.1 1.7 4.2 3.1 4.7 3.2>;
say @a.unique(:as(sub ($val) {$val.Int}));
输出:
(1.1 4.2 3.1)
在docs中解释了如何在调用.unique
之前标准化列表的元素:
The optional :as parameter allows you to normalize/canonicalize the elements before unique-ing. The values are transformed for the purposes of comparison, but it's still the original values that make it to the result list.
并给出以下示例:
say <a A B b c b C>.unique(:as(&lc)) # OUTPUT: «(a B c)»
如果我想让一个有理数列表唯一,只比较它们的整数部分怎么办? :as
后括号内的Int
方法应该怎么调用?
my @a = <1.1 1.7 4.2 3.1 4.7 3.2>;
say @a.unique(:as(?????)) # OUTPUT: «(1.1 4.2 3.1)»
更新:
在@Håkon 的
> say @a.unique(:as({$^a.Int}));
(1.1 4.2 3.1)
或
> say @a.unique(as => {$^a.Int});
(1.1 4.2 3.1)
没有$^a
可以吗?
UPD2: 是的,就在这里!
> say @a.unique(as => *.Int);
(1.1 4.2 3.1)
或
> say (3, -4, 7, -1, 1, 4, 2, -2, 0).unique(as => *²)
> (3 -4 7 -1 2 0)
或
> say @a.unique: :as(*.Int);
(1.1 4.2 3.1)
一种方法是将 anonymous 子例程传递给 unique
。例如:
my @a = <1.1 1.7 4.2 3.1 4.7 3.2>;
say @a.unique(:as(sub ($val) {$val.Int}));
输出:
(1.1 4.2 3.1)