Define a primitive data type: Difference between revisions

Content added Content deleted
Line 591: Line 591:
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 = private Cons(var value)
<lang dyalect>type TinyInt(Integer value) {
throw @Overflow(value) when value is <1 or >10
} with Lookup, Show
func Integer.ToInteger() => this

static func TinyInt.TinyInt(Integer x) {
func TinyInt as Integer => this.value
throw Error.Overflow(x) when x is <1 or >10
TinyInt.Cons(x)
}
func TinyInt.ToString() => "TinyInt (\(this.ini.value))"
func TinyInt.ToInteger() => this.value
func TinyInt + (other) => TinyInt(this.value + other.ToInteger())
func TinyInt + (other) => TinyInt(this.value + other as Integer)
func TinyInt * (other) => TinyInt(this.value * other.ToInteger())
func TinyInt * (other) => TinyInt(this.value * other as Integer)
func TinyInt - (other) => TinyInt(this.value - other.ToInteger())
func TinyInt - (other) => TinyInt(this.value - other as Integer)
func TinyInt / (other) => TinyInt(this.value / other.ToInteger())</lang>
func TinyInt / (other) => TinyInt(this.value / other as Integer)</lang>


Sample usage (interactive session):
Sample usage (interactive session):
Line 620: Line 613:


dy>x * 2
dy>x * 2
Operation overflows</pre>
Runtime exception Dy601: Overflow.
Stack trace: ...</pre>


=={{header|E}}==
=={{header|E}}==