Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

raku

In the docs, it is explained how to normalize the elements of a list before calling .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.

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 a list of rational numbers unique, comparing only their integer part? How should I call Int method inside the 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: On the basis of @Håkon's answer, I've 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)

Is it possible to do it without $^a?

UPD2: Yes, here 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)
like image 304
Eugene Barsky Avatar asked Oct 18 '22 03:10

Eugene Barsky


1 Answers

One way would be to pass an anonymous sub routine to unique. For example:

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)
like image 53
Håkon Hægland Avatar answered Oct 21 '22 07:10

Håkon Hægland