Jump to content

Define a primitive data type: Difference between revisions

m
auto syntax highlight fix
m (syntax highlighting fixup automation)
m (auto syntax highlight fix)
Line 751:
=== 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.
<LANGsyntaxhighlight>DECIMAL
: CLIP ( n lo hi -- n') ROT MIN MAX ;
: BETWEEN ( n lo hi -- flag) 1+ WITHIN ;
Line 759:
: SAFE! ( n addr -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
! ;</LANGsyntaxhighlight>
Testing
<LANGsyntaxhighlight>VARIABLE X
7 X SAFE! X ? 7 ok
12 X CLIP! X ? 10 ok
Line 771:
$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.
<LANGsyntaxhighlight>DECIMAL
: FAST! ( n addr -- ) ! ; ( alias the standard version)
 
Line 782:
: LIMITS-ON ( -- ) ['] SAFE! IS ! ;
: LIMITS-OFF ( -- ) ['] FAST! IS ! ;
: CLIPPING-ON ( -- ) ['] CLIP! IS ! ; </LANGsyntaxhighlight>
 
Testing
<LANGsyntaxhighlight>VARIABLE Y
 
LIMITS-OFF ok
Line 807:
$7FAA2B0C throw
$7FAD4460 c(abort")
</syntaxhighlight>
</LANG>
=== 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.
<LANGsyntaxhighlight>: (->) ( n <text> -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
>BODY ! ;
Line 819:
IF POSTPONE ['] POSTPONE (->) \ compiling action
ELSE ' (->) \ interpret action
THEN ; IMMEDIATE</LANGsyntaxhighlight>
 
Test
<LANGsyntaxhighlight>0 VALUE Z ok
99 TO Z ok ( normal assignment)
Z . 99 ok
Line 831:
$7FAA2B0C throw
$7FAD4570 c(abort")
$7FAD45DC (->)</LANGsyntaxhighlight>
 
=={{header|Fortran}}==
140

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.