T M
class IntStr
Error ReportCollection examples

Dual value integer and string

class IntStr is Int is Str { }

The dual value types (often referred to as allomorphs) allow for the representation of a value as both a string and a numeric type. Typically they will be created for you when the context is "stringy" but they can be determined to be numbers, such as in some quoting constructs:

my $f = <42>say $f.^name# OUTPUT: «IntStr␤»

As a subclass of both Int and Str, an IntStr will be accepted where either is expected. However, IntStr does not share object identity with Int- or Str-only variants:

my $int-str = <42>;
my Int $int = $int-str# OK! 
my Str $str = $int-str# OK! 
say 42  <42  55  1>;   # False; ∈ operator cares about object identity

Methods

method new

method new(Int $iStr $s)

The constructor requires both the Int and the Str value, when constructing one directly the values can be whatever is required:

my $f = IntStr.new(42"forty two");
say +$f# OUTPUT: «42␤» 
say ~$f# OUTPUT: «"forty two"␤»

method Bool

Defined as:

multi method Bool(IntStr:D: --> Bool:D)

This method may be provided by the parent classes and not implemented in IntStr directly.

Returns False if the invocant is numerically 0, otherwise returns True. String portion is not considered.

method Int

method Int

Returns the integer value of the IntStr.

method Numeric

Defined as:

multi method Numeric(IntStr:D: --> Int:D)
multi method Numeric(IntStr:U: --> Int:D)

The :D variant returns the numeric portion of the invocant. The :U variant issues a warning about using an uninitialized value in numeric context and then returns value 0.

method Real

Defined as:

multi method Real(IntStr:D: --> Int:D)
multi method Real(IntStr:U: --> Int:D)

The :D variant returns the numeric portion of the invocant. The :U variant issues a warning about using an uninitialized value in numeric context and then returns value 0.

method Str

Returns the string value of the IntStr.

method ACCEPTS

Defined as:

multi method ACCEPTS(IntStr:D: Any:D $value)

If $value is Numeric (including another allomorph), checks if invocant's Numeric part ACCEPTS the $value. If $value is Str, checks if invocant's Str part ACCEPTS the $value. If value is anything else, checks if both Numeric and Str parts ACCEPTS the $value.

say <5> ~~ "5.0"# OUTPUT: «False␤» 
say <5> ~~  5.0 ; # OUTPUT: «True␤» 
say <5> ~~ <5.0># OUTPUT: «True␤»

Operators

infix cmp

multi sub infix:<cmp>(IntStr:D $aIntStr:D $b)

Compare two IntStr objects. The comparison is done on the Int value first and then on the Str value. If you want to compare in a different order then you would coerce to an Int or Str value first:

my $f = IntStr.new(42"smaller");
my $g = IntStr.new(43"larger");
say $f cmp $g;          # OUTPUT: «Less␤» 
say $f.Str cmp $g.Str;  # OUTPUT: «More␤»