13

I have an array:

my @e = <60.922    20.946     8.721     7.292     4.306     2.821     2.765     2.752     2.741     2.725>

I would like to divide every element in the array by the minimum, however

@e /= @e.min

produced a single element, which isn't correct.

I've read https://docs.raku.org/type/Array but I don't understand the basic elements of Raku for this.

How can I divide every item in the array by the same number?

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
con
  • 5,767
  • 8
  • 33
  • 62

3 Answers3

15

You can use the raku hyper & compound metaoperators like this:

@a >>/=>> @a.min

  • >>X>> means "apply operator X over all list items (with more items on the left)"
  • /= means "assign result of divide operator / to replace each original left hand item"

Use / instead of /= if you want to return the list of results but leave @a unchanged functional programming style.

[Edited according to @lizmat & @Sebastian comments]

librasteve
  • 6,832
  • 8
  • 30
8
my @a = 2, 3, 5, 7, 10;
my $div = @a.min;
$_ /= $div for @a;
say @a;  # [1 1.5 2.5 3.5 5]

When you iterate over an array, you get mutable elements.

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
4
put @e.map( * / @e.min );

OR

put @e.map: * / @e.min;

Sample Input:

my @e = <60.922  20.946  8.721  7.292  4.306  2.821  2.765  2.752  2.741  2.725>;

Sample Output:

22.356697 7.686606 3.200367 2.675963 1.580183 1.035229 1.014679 1.009908 1.005872 1

If you want to continue working with the resultant values, assign the output to a new variable. Or overwrite the original @e array using the .= "back-assignment" operator [ short for @e = @e.map( … ) ]. In the Raku REPL:

~$ raku
Welcome to ™ v2021.06.
Implementing the ™ programming language v6.d.
Built on MoarVM version 2021.06.

To exit type 'exit' or '^D'
> my @e = <60.922  20.946  8.721  7.292  4.306  2.821  2.765  2.752  2.741  2.725>;
[60.922 20.946 8.721 7.292 4.306 2.821 2.765 2.752 2.741 2.725]
> @e .= map( * / @e.min );
[22.356697 7.686606 3.200367 2.675963 1.580183 1.035229 1.014679 1.009908 1.005872 1]
> put @e;
22.356697 7.686606 3.200367 2.675963 1.580183 1.035229 1.014679 1.009908 1.005872 1
>
jubilatious1
  • 1,999
  • 10
  • 18