Define a primitive data type: Difference between revisions

Added Dyalect programming language
(Added Dyalect programming language)
Line 429:
assert(j > i);
}</lang>
=={{header|Dyalect}}==
 
The code below defines a new type <code>TinyInt</code>, provides bounds checking and implementation of all standard arithmetic operators:
 
<lang dyalect>type TinyInt
 
private func getInteger(x) {
match x {
Integer => x,
TinyInt => x.toInteger(),
_ => throw "Type \"\(x.getType().name)\" is not supported by this operation."
}
}
 
private func boundsCheck(x) {
if x < 1 || x > 10 {
throw "Overflow."
}
x
}
 
static func TinyInt.TinyInt(i) {
new(boundsCheck(Integer(i)))
}
 
func TinyInt.toString() {
valueof(this).toString()
}
 
func TinyInt.toInteger() {
valueof(this)
}
 
func TinyInt + (other) {
const z = valueof(this) + getInteger(other)
TinyInt(z)
}
 
func TinyInt * (other) {
const z = valueof(this) * getInteger(other)
TinyInt(z)
}
 
func TinyInt - (other) {
const z = valueof(this) - getInteger(other)
TinyInt(z)
}
 
func TinyInt / (other) {
const z = valueof(this) / getInteger(other)
TinyInt(z)
}</lang>
 
Sample usage (interactive session):
 
<pre>dy>var x = TinyInt(3)
 
dy>x += 4
7 :: TinyInt
 
dy>x * 2
Runtime exception Dy601: Overflow.
Stack trace:
at boundsCheck(Dyalect.Debug.Par) in <stdio>, line 13, column 9
at TinyInt(Dyalect.Debug.Par) in <stdio>, line 19, column 29
at *(Dyalect.Debug.Par) in <stdio>, line 37, column 13
at <external code>
at TinyInt(Dyalect.Debug.Par) in <stdio>, line 19, column 29
at *(Dyalect.Debug.Par) in <stdio>, line 37, column 13
at <external code></pre>
 
=={{header|E}}==
<lang e>def MyNumber := 1..10
Anonymous user