home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / programming / a293_1 / !AForth_Examples_DataStruct < prev    next >
Encoding:
Text File  |  1993-04-13  |  2.0 KB  |  68 lines

  1. \ Forth source file
  2. \ Copyright Mads Meisner-Jensen, 6 Apr 1993
  3. \ Examples of data structures
  4.  
  5. \ Array words _________________________________________________________________
  6.  
  7. \ Dumb array of u chars.
  8. \ Compilation: ( u "name" -- )
  9. : ARRAY  ( -- a-addr )  CREATE CHARS ALLOT ALIGN ;
  10.  
  11. \ Array of u cells.
  12. \ Compilation: ( u "name" -- )
  13. : 1ARRAY  ( i -- a-addr )
  14.   CREATE CELLS ALLOT  DOES> SWAP CELLS + ;
  15.  
  16. \ Double cell array of u double cells.
  17. \ Compilation: ( u "name" -- )
  18. : 2ARRAY  ( i -- a-addr )  
  19.   CREATE 2* CELLS ALLOT  DOES> SWAP 2* CELLS + ;
  20.  
  21. \ String array of u1 strings, each of u2 chars. First string is aligned.
  22. \ Compilation: ( u1 u2 "name" -- )
  23. : $ARRAY  ( i -- c-addr )
  24.   CREATE DUP ,  * CHARS ALLOT ALIGN  DOES> SWAP OVER @ * CHARS + CELL+ ;
  25.  
  26.  
  27. \ Record data structure handling (called 'struct' in C) _______________________
  28.  
  29. \ Defining word, which creates RECORD: as another defining word.
  30. : RECORD:  ( "name" -- sys )
  31.   CREATE HERE 0 ,  0
  32.   DOES> POSTPONE CREATE  @ ALLOT  DOES> + ;
  33. : MEMBER  ( sys -- sys )   OVER  CONSTANT  + ALIGNED ;
  34. : ;RECORD  ( sys -- )  SWAP ! ;
  35.  
  36.  
  37. \ Example of usage of RECORD words
  38.  
  39. RECORD: CUSTOMER    \ define a new record type called CUSTOMER
  40.   20 CHARS MEMBER NAME    \ specify size and name of each member of the record
  41.    1 CELLS MEMBER CASH
  42.    1 CELLS MEMBER ID
  43. ;RECORD
  44.  
  45. \ Define word to display contents of a record
  46. : CUSTOMER.  ( a-addr -- )
  47.   CR ." Name = "  DUP NAME + COUNT TYPE
  48.   CR ." Cash = "  DUP CASH + @ .
  49.   CR ." Id   = "      ID + @ .
  50. ;
  51.  
  52. CUSTOMER SMITH        \ make an instantiation of CUSTOMER called SMITH
  53. CUSTOMER JONES        \ ditto JONES
  54.  
  55. : TEST-RECORD  ( -- )
  56.   S" Nick Smith"    \ intialise name of SMITH record
  57.   NAME SMITH  2DUP C!
  58.   CHAR+ SWAP MOVE
  59.   22381  CASH SMITH !    \ initialise CASH field of SMITH record
  60.   19660412  ID SMITH !    \ initialise ID field of SMITH record
  61.   S" Jim Jones"
  62.   NAME JONES  2DUP C!  CHAR+ SWAP MOVE
  63.   -2347  CASH JONES !
  64.   18990101  ID JONES !
  65.   0 SMITH CUSTOMER.    \ note the zero preceding the record name, when it
  66.   0 JONES CUSTOMER.    \ is to be printed.
  67. ;
  68.