develooper Front page | perl.perl6.users | Postings from October 2021

A nice touch

Thread Next
From:
Sean McAfee
Date:
October 30, 2021 19:38
Subject:
A nice touch
Message ID:
CANan03ZVGKJNRkic9rpaVak53TJ0-RxQk1=-GZXxfPEu7JBsXg@mail.gmail.com
Recently I was golfing the "hyperfactorial," defined for a number 𝑛 as
𝑛**𝑛 × (𝑛-1)**(𝑛-1) × (𝑛-2)**(𝑛-2) × ... × 1.  I created a quite
concise Raku function:

    { [*] [\*] $_...1 }

The only problem was that this function returns zero for a zero input,
whereas the hyperfactorial of 0 is supposed to be 1.  Of course I could
have just handled zero as a special case, but I hoped to find something
comparably short.  After a bit of thought I tried reversing both the range
and the operator:

    { [*] [\R*] 1..$_ }

It worked!  But I couldn't quite see how.  * is commutative, so isn't it
exactly the same as R*?

It turns out, in Raku it isn't quite the same.  On the operators page, I
found that the R metaoperator produces an operator that reverses the order
of the arguments, but *also* has the opposite associativity.  So, for
example, [\R*] 1..4 reduces from the right, producing the list (4, 12, 24,
24).  Somehow I had formed the idea that Raku operators are left-, right-,
or list-associative, but I was wrong.

Anyway, pretty cool!

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About