Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access callee/this in Raku map code/block

Is it possible to access the "callee" ("this") in Raku map code block and/or whatevercode?

E.g. if one wanted to calculate arithmetic mean

my $data = <1 10 0 7 2> ;
say $data.sum
  / $data ;   # or @$data, same as $data.elems in this numeric context
# OUTPUT: «4␤»

by sum of fractions

say $data.map(* / $data).sum
# OUTPUT: «4␤»

like

<1 10 0 7 2>.map({ $_ / $this }).sum   # but there's no $this

or

<1 10 0 7 2>.map( * / $this ).sum

If not, is there an idiomatic way to do it with only a chain of method calls on the <…> data literal, or different way, without storing the data in variable?

like image 329
mykhal Avatar asked Jul 25 '21 08:07

mykhal


2 Answers

There is not, to my knowledge. You would need to be able to know how many values an iterator will produce.

Under the hood, a foo.map: &callable is basically a:

my $iterator = foo.iterator;
callable($iterator.pull-one) until iterator exhausted;

Note that all knowledge of the source of the iterator is lost at that point: there's just an iterator producing values.

Some types of iterators (the so-called PredictiveIterators can tell you how many values it can still produce without actually producing them. But most iterators are not able to do that.

I guess technically it would be possible for map to check whether it got a PredictiveIterator and set a dynamic variable with the number of values it will produce, which you could then check inside the &callable.

Still, it doesn't feel that this is worth the extra check for all maps and for loops, so I don't think a PR for such a feature would be accepted.

like image 102
Elizabeth Mattijsen Avatar answered Nov 10 '22 21:11

Elizabeth Mattijsen


you could do this, by andthen

<1 10 0 7 2>
andthen .sum / .elems
andthen .say

or

<1 10 0 7 2>
andthen .map: * / .elems
andthen .sum
andthen .say
like image 40
wamba Avatar answered Nov 10 '22 19:11

wamba