develooper Front page | perl.perl6.language | Postings from May 2008

ordinal access to autosorted hashes

Thread Next
From:
Jon Lang
Date:
May 27, 2008 19:32
Subject:
ordinal access to autosorted hashes
Message ID:
ef30550b0805271932s15e9e12ey5d478d2b49272a16@mail.gmail.com
From S09: "The default hash iterator is a property called .iterator
that can be user replaced. When the hash itself needs an iterator for
.pairs, .keys, .values, or .kv, it calls %hash.iterator() to start
one. In item context, .iterator returns an iterator object. In list
context, it returns a lazy list fed by the iterator."

Would it be reasonable to allow hashes to use .[] syntax as something
of a shortcut for ".iterator in list context", thus allowing
autosorted hashes to partake of the same sort of dual cardinal/ordinal
lookup capabilities that lists with user-defined array indices have?
e.g.:

  my %point{Int};
  %point{3} = "Star";
  say %point[0]; # same as 'say %point{3}'
  say %point[1]; # error: asking for the second of one key is nonsense.
  %point{-2} = "Base";
  say %point[0]; # same as 'say %point{-2}'
  say %point[1]; # same as 'say %point{3}'

Mind you, this could get messy with multidimensional keys:

  my %grid{Int;Int};
  %grid{3;-2} = "Star";
  %grid{-2;3} = "Base";
  say %grid[0;1]; # "Base"
  say %grid[1;0]; # "Star"
  say %grid[0;0]; # error? %grid{-2;-2} has never had anything assigned to it.

Still, it could be useful to be able to access an autosorted hash's
keys in an ordinal fashion.

Side issue: S09 doesn't specify whether or not you need to explicitly
declare a hash as autosorted.  I'm assuming that the parser is
supposed to figure that out based on whether or not .iterator is ever
used; but it isn't immediately obvious from reading the "Autosorted
hashes" section.  As well, there might be times when explicitly
declaring a hash as autosorted (or not) might be useful for
optimization purposes.

-- 
Jonathan "Dataweaver" Lang

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