Define a primitive data type: Difference between revisions
m
→{{header|Sidef}}: make the range inclusive
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
m (→{{header|Sidef}}: make the range inclusive) |
||
(6 intermediate revisions by 4 users not shown) | |||
Line 659:
=={{header|Elena}}==
ELENA
<syntaxhighlight lang="elena">import extensions;
sealed struct TinyInt : BaseNumber
{
InvalidArgumentException.raise()
InvalidArgumentException.raise()
string toPrintable()
=> value;
}
public program()
{
console.printLine("4t = ", i);
try▼
console.printLine("8t = ", j);
{▼
console.write("4t + 8t = ");
i + j
}</syntaxhighlight>
{{out}}
<pre>
4t = 4
8t = 8
4t + 8t = A value is out of range
=={{header|Euphoria}}==
Line 751 ⟶ 764:
=== Method 1: Safe Integer Store operators===
Forth is a fetch and store based virtual machine. If we create a safe version of store (!) the programmer simply uses this operator rather than the standard store operator.
<
: CLIP ( n lo hi -- n') ROT MIN MAX ;
: BETWEEN ( n lo hi -- flag) 1+ WITHIN ;
Line 759 ⟶ 772:
: SAFE! ( n addr -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
! ;</
Testing
<
7 X SAFE! X ? 7 ok
12 X CLIP! X ? 10 ok
Line 771 ⟶ 784:
$7FAA2B0C throw
$7FAD4698 c(abort")
</syntaxhighlight>
▲</LANG>
=== Method 2: redefine standard "store" operator as DEFER word ===
Using the code in Method 1, we can re-define the store (!) operator to be switchable.
<
: FAST! ( n addr -- ) ! ; ( alias the standard version)
Line 782 ⟶ 795:
: LIMITS-ON ( -- ) ['] SAFE! IS ! ;
: LIMITS-OFF ( -- ) ['] FAST! IS ! ;
: CLIPPING-ON ( -- ) ['] CLIP! IS ! ; </
Testing
<
LIMITS-OFF ok
Line 807 ⟶ 820:
$7FAA2B0C throw
$7FAD4460 c(abort")
</syntaxhighlight>
=== Method 3: Create a safe VALUE assignment operator===
A VALUE defines a numerical data type that returns it's value rather than an address (pointer) like a variable.
We can create a word that assigns a number to a VALUE but tests for out of range errors.
<
OVER 1 10 BETWEEN 0= ABORT" out of range!"
>BODY ! ;
Line 819 ⟶ 832:
IF POSTPONE ['] POSTPONE (->) \ compiling action
ELSE ' (->) \ interpret action
THEN ; IMMEDIATE</
Test
<
99 TO Z ok ( normal assignment)
Z . 99 ok
Line 831 ⟶ 844:
$7FAA2B0C throw
$7FAD4570 c(abort")
$7FAD45DC (->)</
=={{header|Fortran}}==
Line 2,393 ⟶ 2,406:
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">subset Integer < Number { .is_int }
subset MyIntLimit < Integer { . ~~ (1 ..
class MyInt(value < MyIntLimit) {
Line 2,985 ⟶ 2,998:
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.
<syntaxhighlight lang="
construct new(n) {
if (!(n is Num && n.isInteger && n >= 1 && n <= 10)) {
|