Define a primitive data type: Difference between revisions

m
→‎{{header|Sidef}}: simplified example
(Added EchoLisp)
m (→‎{{header|Sidef}}: simplified example)
Line 1,454:
 
=={{header|Sidef}}==
<lang ruby>classsubset Integer < MyInt(Number value) { .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 }
Line 1,472 ⟶ 1,463:
 
method AUTOLOAD(_, name, *args) {
var result = value.(name)(args.map {|n| Number(n) }...);
result.is_akind_of(Number) &&? MyInt(result.int) : result
 
result.is_a(Number) &&
return MyInt(result.int);
 
result;
}
}
Line 1,484 ⟶ 1,471:
## Tests:
#
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.to_hexas_hex.dump; # => "9" -- an hexadecimal string
 
a -= 7; # a=2
say (a + b); # => 8 -- the result of (2 + 6)
 
a += 4; # a=6
say a+b; # error: Invalidclass value`MyInt` '12';does mustnot bematch between 1 and 10MyInt(12)</lang>
 
=={{header|Tcl}}==
2,747

edits