Define a primitive data type

subset Integer    < Number  { .is_int }
subset MyIntLimit < Integer { . ~~ (1 .. 10) }

class MyInt(value < MyIntLimit) {

    method to_s      { value.to_s }
    method get_value { value.get_value }

    method ==(Number x) { value == x }
    method ==(MyInt  x) { value == x.value }

    method AUTOLOAD(_, name, *args) {
        var results = [value.(name)(args.map {|n| Number(n) }...)]
        results.map{|r| r.kind_of(Number) ? MyInt(r.int) : r}...
    }
}

#
## Example:
#
var a = MyInt(2)    # creates a new object of type `MyInt`
a += 7              # adds 7 to a
say a               # => 9
say a/2             # => 4

var b = (a - 3)     # b is of type `MyInt`
say b               # => 6

say a.as_hex.dump   # => "9" -- an hexadecimal string

a -= 6              # a=3
var c = (a + b)     # MyInt(3) + MyInt(6)
say c               # => 9
say c.class         # => MyInt

a *= 2              # a=6
say a+b             # error: class `MyInt` does not match MyInt(12)

Last updated