Define a primitive data type: Difference between revisions

Content added Content deleted
(Added EchoLisp)
m (→‎{{header|Sidef}}: simplified example)
Line 1,454: Line 1,454:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>class MyInt(Number value) {
<lang ruby>subset Integer < Number { .is_int }
subset MyIntLimit < Integer { . ~~ (1 ..^ 10) }


class MyInt(value < MyIntLimit) {
has min = 1;
has max = 10;

method init {
(value > max) || (value < min) && (
die "Invalid value '#{value}': must be between #{min} and #{max}";
);
!value.is_int && (
die "Invalid value '#{value}': must be an integer";
);
}


method to_s { value.to_s }
method to_s { value.to_s }
Line 1,472: Line 1,463:


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

result.is_a(Number) &&
return MyInt(result.int);

result;
}
}
}
}
Line 1,484: Line 1,471:
## Tests:
## Tests:
#
#
var a = MyInt(2); # creates a new object of type `MyInt`
var a = MyInt(2) # creates a new object of type `MyInt`
a += 7; # adds 7 to a
a += 7 # adds 7 to a
say a; # => 9
say a # => 9
say a/2; # => 4
say a/2 # => 4


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


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


a -= 7; # a=2
a -= 7 # a=2
say (a + b); # => 8 -- the result of (2 + 6)
say (a + b) # => 8 -- the result of (2 + 6)


a += 4; # a=6
a += 4 # a=6
say a+b; # error: Invalid value '12'; must be between 1 and 10</lang>
say a+b # error: class `MyInt` does not match MyInt(12)</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==