Define a primitive data type: Difference between revisions

Content added Content deleted
Line 534: Line 534:
The code below defines a new type <code>TinyInt</code>, provides bounds checking and implementation of all standard arithmetic operators:
The code below defines a new type <code>TinyInt</code>, provides bounds checking and implementation of all standard arithmetic operators:


<lang dyalect>type TinyInt
<lang dyalect>type TinyInt using {
var value
private {
func getInteger(x) {
match x {
Integer => x,
TinyInt => x.toInteger(),
_ => throw "Type \"\(x.getType()::name)\" is not supported by this operation."
}
}
func boundsCheck(x) {
if x < 1 || x > 10 {
throw "Overflow"
}
x
}
}
}

func Integer.toInteger() => this
func TinyInt.TinyInt(i) cons {
static func TinyInt.TinyInt(Integer x) {
throw "Overflow" when x is <1 or >10
boundsCheck(Integer(i))
private()::value = x
}
}
func TinyInt.toString() decons {
func TinyInt.toString() => "TinyInt (\(private()::value))"
this.toString()
}
func TinyInt.toInteger() decons {
func TinyInt.toInteger() => private()::value
this
}
func TinyInt + (other) decons {
func TinyInt + (other) => TinyInt(private()::value + other.toInteger())
let z = this + getInteger(other)
TinyInt(z)
}
func TinyInt * (other) decons {
func TinyInt * (other) => TinyInt(private()::value * other.toInteger())
let z = this * getInteger(other)
TinyInt(z)
}
func TinyInt - (other) decons {
func TinyInt - (other) => TinyInt(private()::value - other.toInteger())
let z = this - getInteger(other)
TinyInt(z)
}
func TinyInt / (other) decons {
func TinyInt / (other) => TinyInt(private()::value / other.toInteger())</lang>
let z = this / getInteger(other)
TinyInt(z)
}</lang>


Sample usage (interactive session):
Sample usage (interactive session):
Line 590: Line 562:


dy>x += 4
dy>x += 4
7 :: TinyInt
TinyInt (7) :: TinyInt


dy>x * 2
dy>x * 2
Runtime exception Dy601: Overflow.
Runtime exception Dy601: Overflow.
Stack trace:
Stack trace: ...</pre>
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}}==
=={{header|E}}==