T M
class NumStr
Error ReportCollection examples

Dual value floating-point number and string

class NumStr is Num 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.1e0>say $f.^name# OUTPUT: «NumStr␤»

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

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

Methods

method new

method new(Num $iStr $s)

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

my $f = NumStr.new(42.1e0"forty two and a bit");
say +$f# OUTPUT: «42.1␤» 
say ~$f# OUTPUT: «"forty two and a bit"␤»

method Bool

Defined as:

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

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

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

method Num

method Num

Returns the Num value of the NumStr.

method Numeric

Defined as:

multi method Numeric(NumStr:D: --> Num:D)
multi method Numeric(NumStr:U: --> Num: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 0e0.

method Real

Defined as:

multi method Real(NumStr:D: --> Num:D)
multi method Real(NumStr:U: --> Num: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 0e0.

method Str

Returns the string value of the NumStr.

method ACCEPTS

Defined as:

multi method ACCEPTS(NumStr: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 <5e0> ~~ "5.0"# OUTPUT: «False␤» 
say <5e0> ~~  5.0 ; # OUTPUT: «True␤» 
say <5e0> ~~ <5.0># OUTPUT: «True␤»

Operators

infix cmp

multi sub infix:<cmp>(NumStr:D $aNumStr:D $b)

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

my $f = NumStr.new(42.1e0"smaller");
my $g = NumStr.new(43.1e0"larger");
say $f cmp $g;          # OUTPUT: «Less␤» 
say $f.Str cmp $g.Str;  # OUTPUT: «More␤»