Search code examples
sortinghashmapraku

Sorting hash kv pairs


my %hash =
    two   => 2,
    three => 3,
    one   => 1,
;

for %hash.sort(*.key)>>.kv -> ($key, $value) {
    say "'$key' => '$value'";
}

Is %hash.sort({.key})>>.kv equivalent to above sort?

Why this sort doesn't work without hyper >> hint?


Solution

  • The sort method is returning a List of Pairs.

    Since calling .kv on the list returns a list of index, Pair lists, which you don't want; you can't just call .kv. So you have to pull out the key and value from the Pair objects in the list individually by calling the .kv method on each of them, which >>.kv does.

    You could also have used .map(*.kv) instead.

    The >>.kv syntax allows an implementation to spread the work over multiple threads if it makes sense to do so.
    ( Currently Rakudo just does the work in a semi-random order to prevent people from using the feature wrong )


    There is an alternate way of writing the loop by extracting the attributes using adverbs in the sub-signature:

    for %hash.sort -> (:$key, :$value) {
      say "'$key' => '$value'";
    }
    
    for %hash.sort -> $pair (:$key, :$value) {
      say $pair;
      say $key === $pair.key and $value === $pair.value; # True␤
    }
    
    # :$key is short for :key($key)
    for %hash.sort -> (:key($k), :value($v)) {
      say "'$k' => '$v'";
    }
    

    This can be useful on other objects which don't have a method for creating a list of their public attributes

    class C { has $.a; has $.b; has $.c; has $!private-value }
    my $c = 5;
    my $obj = C.new(:a<A>,:b(1),:$c);
    
    given $obj -> ( :$a, :b($b), :$c) ) {
      say "$a $b $c";
    }
    
    # ignore $.a by using an unnamed scalar
    given $obj -> ( :a($), :$b, :$c ) { ... }
    
    # places any unspecified public attributes in %others
    given $obj -> ( :$a, :$b, *%others ) {
      .say for keys %others; # c␤
    }
    
    # ignores any unspecified attributes
    # useful to allow subclasses to add more attributes
    # or to just drop any values you don't care about
    given $obj -> ( :$a, :$b, *% ) { ... }
    
    # fails because it doesn't handle the public c attribute
    # in the sub-signature
    given $obj -> ( :$a, :$b ) { ... }
    

    That is only the beginning of what's possible with signatures.

    All of the following is also allowed in subroutine and method signatures, optional, and completely overkill for this example. It is really useful in multi subs and multi methods for restricting the possible candidates.

    for 'one' => 1, 1/3
    ->
      # Type is an alias to the object type
      ::Type Any $_ # Any is the default type requirement
    
      # the public attributes of the object
      (
        ::A-Type Any :key(   :numerator(   $a ) ),
        ::B-Type Any :value( :denominator( $b ) ) where $b >= 1,
      )
    {
      my Type $obj = $_; # new variable declared as having the same type
      my A-Type $new-a = $a;
      my B-Type $new-b = $b;
    
      # could have used $_.^name or .^name instead of Type.^name
      # so you don't actually have to add the alias to the signature
      # to get the name of the arguments type
      say Type.^name, ' ', $_;
      say '  ', A-Type.^name, ' ', $a;
      say '  ', B-Type.^name, ' ', $b;
    }
    
    Pair one => 1
      Str one
      Int 1
    Rat 0.333333
      Int 1
      Int 3
    

    As to using .sort({.key}), yes that is basically the same thing, as sort accepts anything Callable there.

    I would like to point out that you didn't even need to provide an argument to sort because it's default is even smarter than what you gave it.

    Perl 6 has many ways of creating and accessing Callable things. So any of the following would have worked:

    *.key
    { .key } # { $_.key }
    -> $_ { .key } # basically what the previous line turns into
    { $^placeholder-var.key }
    sub ($_) { .key }
    &a-subroutine-reference # you would have to create the subroutine though
    

    Also since all of the normal operators are actually subroutines, you could use them in other places where you need a Callable. ( I can't think of one that works in that spot though )

    &infix:<+> # the subroutines responsible for the numeric addition operator
    &[+] # ditto
    
    &prefix:<++>
    &postfix:<++>
    
    # etc