Define a primitive data type: Difference between revisions

Added Wren
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
(Added Wren)
Line 2,690:
THIS.lHasError = .T.
ENDDEFINE</lang>
 
=={{header|Wren}}==
To do this in Wren, you need to define a new TinyInt class with a suitable constructor and re-implement all the operators which apply to integers, checking (in the case of those that return an integer) that the result is within bounds and throwing an error if it isn't.
 
Note that inheriting from the basic types, such as Num, is not recommended.
 
The following carries out this procedure for a few basic operations and shows examples of their usage including throwing an out of bounds error on the last one.
<lang ecmascript>class TinyInt {
construct new(n) {
if (!(n is Num && n.isInteger && n >= 1 && n <= 10)) {
Fiber.abort("Argument must be an integer between 1 and 10.")
}
_n = n
}
 
n { _n }
 
+(other) {
var res = _n + other.n
if (res < 1 || res > 10) Fiber.abort("Result must be an integer between 1 and 10.")
return TinyInt.new(res)
}
 
-(other) {
var res = _n - other.n
if (res < 1 || res > 10) Fiber.abort("Result must be an integer between 1 and 10.")
return TinyInt.new(res)
}
 
*(other) {
var res = _n * other.n
if (res < 1 || res > 10) Fiber.abort("Result must be an integer between 1 and 10.")
return TinyInt.new(res)
}
 
/(other) {
var res = (_n / other.n).truncate
if (res < 1 || res > 10) Fiber.abort("Result must be an integer between 1 and 10.")
return TinyInt.new(res)
}
 
==(other) { _n == other.n }
!=(other) { _n != other.n }
 
toString { _n.toString }
}
 
var a = TinyInt.new(1)
var b = TinyInt.new(2)
var c = a + b
System.print("%(a) + %(b) = %(c)")
var d = c - a
System.print("%(c) - %(a) = %(d)")
var e = d / d
System.print("%(d) / %(d) = %(e)")
var f = c * c
System.print("%(c) * %(c) = %(f)")
System.print("%(a) != %(b) -> %(a != b)")
System.print("%(a) + %(a) == %(b) -> %((a + a) == b)")
var g = f + b // out of range error here</lang>
 
{{out}}
<pre>
1 + 2 = 3
3 - 1 = 2
2 / 2 = 1
3 * 3 = 9
1 != 2 -> true
1 + 1 == 2 -> true
Result must be an integer between 1 and 10.
[./primitive line 11] in +(_)
[./primitive line 48] in (script)
</pre>
 
{{omit from|AWK}}
{{omit from|Axe}}
9,485

edits