Using .unique (: as ...) with numbers in Perl 6

The docs explain how to normalize list items before calling .unique:

Optional parameter: as allows you to normalize / canonize elements before unique. Values ​​are converted for comparison purposes, but these are still the original values ​​that make this a list of results.

and the following example is given:

say <a A B b c b C>.unique(:as(&lc))          # OUTPUT: «(a B c)␤»

What if I want to make the list of rational numbers unique by comparing only their integer part? How can I call the method Intin parentheses after :as?

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)␤»

UPD: Based on @ Håkon's answer, I found the following solution:

> say @a.unique(:as({$^a.Int}));
(1.1 4.2 3.1)

or

> say @a.unique(as => {$^a.Int});
(1.1 4.2 3.1)

Can this be done without $^a?

UPD2: Yes, there it is!

> say @a.unique(as => *.Int);
(1.1 4.2 3.1)

or

> say (3, -4, 7, -1, 1, 4, 2, -2, 0).unique(as => *²)
> (3 -4 7 -1 2 0)

or

> say @a.unique: :as(*.Int);
(1.1 4.2 3.1)
+4
source share
1 answer

One way would be to pass the anonymous routine to unique. For instance:

my @a = <1.1 1.7 4.2 3.1 4.7 3.2>;
say @a.unique(:as(sub ($val) {$val.Int})); 

Output

(1.1 4.2 3.1)
+3
source

Source: https://habr.com/ru/post/1688806/


All Articles