[% setvar title Operators: Polymorphic comparisons %]

This file is part of the Perl 6 Archive

Note: these documents may be out of date. Do not use as reference!

To see what is currently happening visit http://www.perl6.org/


Operators: Polymorphic comparisons


  Maintainer: Damian Conway <damian@conway.org>
  Date: 7 Aug 2000
  Last Modified: 18 Sep 2000
  Mailing List: perl6-language@perl.org
  Number: 54
  Version: 2
  Status: Frozen


This RFC proposes that numeric comparison operators default to stringwise comparison when both arguments are non-numeric strings.


Currently the expression:

	"cat" == "dog"

returns true.

It is proposed that if neither argument of a numeric comparison operator can be converted to a number, rather than both being converted to zero, the two operands should be compared using the equivalent stringwise comparison operator.

It is further proposed that the current warning:

        Argument "%s" isn't numeric

be changed to:

        Arguments of "%s" aren't numeric - using string comparison instead


Perl has excellent support for generic programming, because of its dynamic typing, generic data types, and interface polymorphism. Just about the only place where that DWIM genericity breaks down is in comparisons.

It is difficult to construct many generic algorithms and data structures in Perl, because there is no generic way to specify an ordering on dynamically typed data. For example, one cannot simply code a generic BST insertion method:

        sub insert
                my ($self, $key, $value) = @_;
                if (!defined($self->{key}))
                        $self->{key} = $key;
                        return $self->{value} = $value;
                my $compare = $key <=> $self->{key};
                return $self->{value} = $value unless $compare;

                $self->{$compare} = $self->new() unless $self->{$compare};
                return $self->{$compare}->insert($key,$value);

This will work well for numeric keys, but fail miserably on most string-based keys, because <=> will generally return 0 for most pairs of strings.

The above code would work correctly however if <=> detected the string/string comparison and automagically used cmp instead.


Dammit, Jim, I'm a doctor, not an engineer!


Chapter 12 of "Object Oriented Perl"