### Re: Euclidean algorithm Golf in Perl 6

by moritz (Cardinal)
 on Jun 18, 2009 at 16:28 UTC ( #772778=note: print w/replies, xml ) Need Help??

in reply to Euclidean algorithm Golf in Perl 6

Two simple things you can do (also in Perl 5):

You can get rid of the temporary \$t by using list assignment:

```    while \$b != 0 {
(\$b, \$a) = (\$a % \$b, \$b);
}

Or you can resort to recursion, ignoring your boundaries to the golf court:

```sub gcd (\$a, \$b) {
return \$a if !\$b;
gcd(\$b, \$a % \$b);
}

say gcd(24, 42);

For none of these I can see something where Perl 6 really plays its strengths.

So maybe something completely else? This might work, but since nobody implements infix:<...> yet, I couldn't test it:

```sub gcd (\$a, \$b) {
(\$a, \$b ... { \$^x % \$^y || () })[*-1]
}

For example for gcd(42, 24) it would produce the list 42, 24, 18, 6. During the next call to the block it the \$^x % \$^y returns 0, and the block the empty list, ending the creation of the list. The last element is the gcd.

Replies are listed 'Best First'.
Re^2: Euclidean algorithm Golf in Perl 6
by John M. Dlugosz (Monsignor) on Jun 19, 2009 at 14:30 UTC
The last one is very interesting. Wouldn't the original arguments need to be sorted first, though? I think it only works if \$a >= \$b. Looking back at the original, it is the same way. The wikipedia article requires this for the modulo version (as well as the recursive version), but not for the subtraction version.

Your last one vividly illustrates how the algorithm generates successive refinements.

I also suppose that the "Golf" module, which would create 1-char Unicode aliases for a bunch of things, should include a symbol to mean "recursive call". Besides being shorter than naming the function again, you may want to do it with unnamed blocks, and &?ROUTINE is also rather verbose. ↺ perhaps?

Create A New User
Node Status?
node history
Node Type: note [id://772778]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2018-02-22 11:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When it is dark outside I am happiest to see ...

Results (291 votes). Check out past polls.

Notices?