Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Prototype like sort()?

by Laurent_R (Canon)
on Jan 27, 2018 at 22:58 UTC ( [id://1208002]=note: print w/replies, xml ) Need Help??


in reply to Prototype like sort()?

FWIW, this is an implementation in Perl of an exotic sort algorithm, comb sort (or Dobosiewicz's sort - see https://en.wikipedia.org/wiki/Comb_sort for details), using prototypes to mimic Perl's internal sort function:
sub comb_sort (&\@) { my $code_ref = shift; my $v_ref = shift; my $max = scalar (@$v_ref); my $gap = $max; while (1) { my $swapped = 0; $gap = int ($gap / 1.3); $gap = 1 if $gap < 1; my $lmax = $max - $gap - 1; foreach my $i (0..$lmax) { local ($a, $b) = ($$v_ref[$i], $$v_ref[$i+$gap]); ($$v_ref[$i], $$v_ref[$i+$gap], $swapped) = ($$v_ref[$i+$g +ap], $$v_ref[$i], 1) if $code_ref->($a, $b) > 0; } last if $gap == 1 and $swapped == 0; } }
This sort subroutine can be called with a code block just as Perl's internal sort. For example:
#!/usr/bin/perl use strict; use warnings; my @v; my $max = 500; $v[$_] = int rand(20000) foreach (0..$max); comb_sort {$a<=>$b} @v; print "@v";
I'm not sure that's what you're after, but you can see above a calling syntax with a simple code block (no need to build an actual subroutine).

Replies are listed 'Best First'.
Re^2: Prototype like sort()?
by perlancar (Hermit) on Jan 29, 2018 at 13:47 UTC

    Yup, not quite. sort can be called without a block, while using the & prototype means your sub has to be called with a block. Perhaps if Perl supported a prototype like [&@$] like it does \[&@$].

      Yes, right, this syntax allows only the block syntax, not the expression syntax. And I don't think there is any simple way to enable an expression syntax for such a sort subroutine (or for a custom clone of the map or grep functions).

      But that does not deprive you of any functionality: any sort construct using the sort expression syntax can be easily transformed into a block syntax, essentially by adding a pair of curly brackets and removing the comma.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1208002]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-18 20:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found