Ordered partitions: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (→‎{{header|Perl}}: future-proof for 5.36)
Line 1,882: Line 1,882:


=={{header|Perl}}==
=={{header|Perl}}==
===Threaded Generator Method===
Code 1: threaded generator method. This code demonstrates how to make something like Python's
This code demonstrates how to make something like Python's
generators or Go's channels by using Thread::Queue. Granted, this is horribly inefficient, with constantly creating and killing threads and whatnot (every time a partition is created, a thread is made to produce the next partition, so thousands if not millions of threads live and die, depending on the problem size). But algorithms are often more naturally expressed in a coroutine manner -- for this example, "making a new partition" and "picking elements for a partition" can be done in separate recursions cleanly if so desired. It's about 20 times slower than the next code example, so there.
generators or Go's channels by using Thread::Queue. Granted, this is horribly inefficient, with constantly creating and killing threads and whatnot (every time a partition is created, a thread is made to produce the next partition, so thousands if not millions of threads live and die, depending on the problem size). But algorithms are often more naturally expressed in a coroutine manner -- for this example, "making a new partition" and "picking elements for a partition" can be done in separate recursions cleanly if so desired. It's about 20 times slower than the next code example, so there.


<syntaxhighlight lang="perl">use Thread 'async';
<syntaxhighlight lang="perl">use strict;
use warnings;
use Thread 'async';
use Thread::Queue;
use Thread::Queue;


Line 1,911: Line 1,914:
};
};


$q = new Thread::Queue;
$q = Thread::Queue->new;
(async{ &$gen; # start the main work load
(async{ &$gen; # start the main work load
$q->enqueue(undef) # signal that there's no more data
$q->enqueue(undef) # signal that there's no more data
Line 1,927: Line 1,930:
print "@$a | @$b | @$rb\n";
print "@$a | @$b | @$rb\n";
}
}
}</syntaxhighlight>
}
</syntaxhighlight>


Code 2: Recursive solution.
===Recursive solution===
{{trans|Raku}}
{{trans|Raku}}
<syntaxhighlight lang="perl">use List::Util 1.33 qw(sum pairmap);
<syntaxhighlight lang="perl">use strict;
use warnings;
use List::Util 1.33 qw(sum pairmap);


sub partition {
sub partition {