Define a primitive data type: Difference between revisions

Line 547:
=={{header|Forth}}==
{{ works with|ANS/ISO Forth|}}
Standard Forth does not type data but it does "type" words that act on data. However trueTrue to the low level nature of Forth the responsibility to select the correct action word for specific data is given to the programmer. That being said there are some simple ways to add the requested mechanism to your Forth system.
 
=== Method 1: Safe Integer Store operatoroperators===
Forth is fetch and store based virtual machine. If we create a safe versionversions of store (!) the programmer simply uses this operator rather than the standard store operator.
<LANG>DECIMAL
: BETWEENCLIP ( n lo hi -- n') 1+ROT MIN WITHINMAX ;
: BETWEEN ( n lo hi -- flag) 1+ WITHIN ;
 
\ programmer chooses CLIPPED or SAFE integer assignment
: CLIP! ( n addr -- ) SWAP 1 10 CLIP SWAP ! ;
: SAFE! ( n addr -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
! ;
\ testing
VARIABLE X
7 X SAFE! X ? 7 ok
12 X CLIP! X ? 10 ok
 
VARIABLE X
7 X SAFE! ok
X ? 7 ok
99 X SAFE!
:64: out of range!
Line 569 ⟶ 573:
</LANG>
=== Method 2: redefine standard "store" operator as DEFER word ===
IfUsing usingthe acode specialin storeMethod operator is not-acceptable1, we can re-define the store (!) operator to be switchable with limits on or off.
<LANG>DECIMAL
: BETWEEN ( n lo hi -- ) 1+ WITHIN ;
 
: FAST! ( n addr -- ) ! ; ( alias the standard version)
: SAFE! ( n addr -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
! ;
 
DEFER !
 
\ commands to change the action of '!'
: LIMITS-ON ( -- ) ['] SAFE! IS ! ;
: LIMITS-OFF ( -- ) ['] FAST! IS ! ;
: CLIPPING-ON ( -- ) ['] CLIP! IS ! ;
 
VARIABLE Y
Anonymous user