| 1 | package SPVM::Comparator; | ||
| 2 | |||
| 3 | 1; | ||
| 4 | |||
| 5 | =head1 Name | ||
| 6 | |||
| 7 | SPVM::Comparator - Interface Type for Object Comparation Callback | ||
| 8 | |||
| 9 | =head1 Usage | ||
| 10 | |||
| 11 | use Comparator; | ||
| 12 | use Point; | ||
| 13 | |||
| 14 | my $comparator = (Comparator)method : int ($object1 : object, $object2 : object); { | ||
| 15 | my $point1 = (Point)$object1; | ||
| 16 | my $point2 = (Point)$object2; | ||
| 17 | |||
| 18 | if ($point1->x > $point2->x) { | ||
| 19 | return 1; | ||
| 20 | } | ||
| 21 | elsif ($point1->x < $point2->x) { | ||
| 22 | return -1; | ||
| 23 | } | ||
| 24 | else { | ||
| 25 | return 0; | ||
| 26 | } | ||
| 27 | }; | ||
| 28 | |||
| 29 | my $point1 = Point->new(1, 2); | ||
| 30 | my $point2 = Point->new(5, 6); | ||
| 31 | my $result = $comparator->($point1, $point2); | ||
| 32 | |||
| 33 | =head1 Description | ||
| 34 | |||
| 35 | C<Comparator> is the interface type for the object comparation callback. | ||
| 36 | |||
| 37 | =head1 Interface Methods | ||
| 38 | |||
| 39 | C<required method : int ($object1 : object, $object2 : object);> | ||
| 40 | |||
| 41 | This method must receive two objects and return the following value. | ||
| 42 | |||
| 43 | If the first argument is greater than the second argument, returns 1. If the first argument is lower than the second argument, returns -1. If the first argument is equal to the second argument, returns 0. | ||
| 44 | |||
| 45 | =head1 Class Methods | ||
| 46 | |||
| 47 | =head2 default_comparator | ||
| 48 | |||
| 49 | C<static method default_comparator : L<Comparator|SPVM::Comparator> ();> | ||
| 50 | |||
| 51 | Returns a default comparator. | ||
| 52 | |||
| 53 | The implementation of the default comparator is | ||
| 54 | |||
| 55 | method : int ($object1 : Comparable, $object2 : Comparable) { | ||
| 56 | |||
| 57 | my $cmp = 0; | ||
| 58 | if ($object1 && $object2) { | ||
| 59 | $cmp = $object1->cmp($object1, $object2); | ||
| 60 | } | ||
| 61 | elsif ($object1) { | ||
| 62 | $cmp = 1; | ||
| 63 | } | ||
| 64 | elsif ($object2 ) { | ||
| 65 | $cmp = -1; | ||
| 66 | } | ||
| 67 | |||
| 68 | return $cmp; | ||
| 69 | } | ||
| 70 | |||
| 71 | return $default_comparator; | ||
| 72 | } | ||
| 73 | |||
| 74 | If $object1 and $object2 are defined, the comparison is perfermed by L<Comparable#cmp|SPVM::Comparable/"cmp"> method in the class of $object1, and returns its return value. | ||
| 75 | |||
| 76 | If only $object1 is defined, returns 1. | ||
| 77 | |||
| 78 | If only $object2 is defined, returns -1. | ||
| 79 | |||
| 80 | If both $object1 and $object2 are not defined, returns 0. | ||
| 81 | |||
| 82 | =head1 Copyright & License | ||
| 83 | |||
| 84 | Copyright (c) 2023 Yuki Kimoto | ||
| 85 | |||
| 86 | MIT License |