Define a primitive data type: Difference between revisions
Content added Content deleted
(Nimrod -> Nim) |
m (Added the Sidef language) |
||
Line 1,398: | Line 1,398: | ||
val test = (TinyInt.lower to TinyInt.upper).map(n => TinyInt(n.toByte))</lang> |
val test = (TinyInt.lower to TinyInt.upper).map(n => TinyInt(n.toByte))</lang> |
||
=={{header|Sidef}}== |
|||
<lang ruby>class MyInt(value) { |
|||
def min = 1; |
|||
def max = 10; |
|||
method new(value is Number) { |
|||
(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 new(value) { |
|||
die "Invalid value '#{value}'; expected a number"; |
|||
} |
|||
method AUTOLOAD(name, *args) { |
|||
var result = value.(name)(args...); |
|||
result.is_a(Number) && |
|||
return MyInt(result.int); |
|||
result; |
|||
} |
|||
} |
|||
# |
|||
## 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_hex; # => "0x9" -- an hexadecimal string |
|||
say a+b; # error: Invalid value '15'; must be between 1 and 10</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |