Re: Arbitrary mathematical relations, not just hashes

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



From: "Kelly Jones" <kelly.terry.jones@xxxxxxxxx>
> Many programming languages (including Perl, Ruby, and PHP) support hashes:
> 
> $color['apple'] = 'red';
> $color['ruby'] = 'red';
> 
> $type['apple'] = 'fruit';
> $type['ruby'] = 'gem';
> 
> This quickly lets me find the color or type of a given item.
> 
> In this sense, color() and type() are like mathematical functions.
> 
> However, I can't easily find all items whose $color is 'red', nor all
> items whose $type is 'fruit'. In other words, color() and type()
> aren't full mathematical relations.

One of the reasons why you can't find them as easily is efficiency. 
If people could ask for all items in %color whose value is 'red', 
they would. Without noticing that it's much more expensive than the 
other way around.

@items = grep {$color{$_} eq 'red'} keys %color;

is not too complex, but it complex enough to suggest that there is 
more work involved. The only way both the direction could be equaly 
complex would be to keep two hash tables internaly instead of one. 
Which would double the memory consumption.

If you do need to do this more often you can build an inverse data 
structure. Which if it was a one-to-one relation would be just

 %inv_color = reverse %color;

in Perl, of course once the relation is many to one than the inverse 
one will be more complex to build.

  my %inv_color;
  while (my ($k,$v) = each %color) {
    push @{$inv_color{$v}}, $k;
  }

and of course will be harder to work with. But there is no way around 
that.


What is it you are actually trying to acomplish?

Jenda
===== Jenda@xxxxxxxxxxx === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
	-- Terry Pratchett in Sourcery


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux