Define a primitive data type: Difference between revisions

Content added Content deleted
Line 547: Line 547:
=={{header|Forth}}==
=={{header|Forth}}==
{{ works with|ANS/ISO Forth|}}
{{ works with|ANS/ISO Forth|}}
Standard Forth does not type data but it does "type" words that act on data. However true 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.
Standard Forth does not type data but it does "type" words that act on data. True 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 operator===
=== Method 1: Safe Integer Store operators===
Forth is 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.
Forth is fetch and store based virtual machine. If we create a safe versions of store (!) the programmer simply uses this operator rather than the standard store operator.
<LANG>DECIMAL
<LANG>DECIMAL
: BETWEEN ( n lo hi -- ) 1+ WITHIN ;
: CLIP ( n lo hi -- n') ROT MIN MAX ;
: 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 -- )
: SAFE! ( n addr -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
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!
99 X SAFE!
:64: out of range!
:64: out of range!
Line 569: Line 573:
</LANG>
</LANG>
=== Method 2: redefine standard "store" operator as DEFER word ===
=== Method 2: redefine standard "store" operator as DEFER word ===
If using a special store operator is not-acceptable we can re-define the store (!) operator to be switchable with limits on or off.
Using the code in Method 1, we can re-define the store (!) operator to be switchable.
<LANG>DECIMAL
<LANG>DECIMAL
: BETWEEN ( n lo hi -- ) 1+ WITHIN ;

: FAST! ( n addr -- ) ! ; ( alias the standard version)
: FAST! ( n addr -- ) ! ; ( alias the standard version)
: SAFE! ( n addr -- )
OVER 1 10 BETWEEN 0= ABORT" out of range!"
! ;


DEFER !
DEFER !


\ commands to change the action of '!'
\ commands to change the action of '!'
: LIMITS-ON ( -- ) ['] SAFE! IS ! ;
: LIMITS-ON ( -- ) ['] SAFE! IS ! ;
: LIMITS-OFF ( -- ) ['] FAST! IS ! ;
: LIMITS-OFF ( -- ) ['] FAST! IS ! ;
: CLIPPING-ON ( -- ) ['] CLIP! IS ! ;


VARIABLE Y
VARIABLE Y