retroforth/example/defstruct.forth
crc 69b14a7ef9 stdlib: set: namespace is now array: - update your code!
FossilOrigin-Name: b5123a7db0c66dccf2071ea6431c6a31d57d20bb1efe4e36a90eb21666ba8d24
2019-02-21 04:19:14 +00:00

37 lines
891 B
Forth

LISP provides a function, `defstruct`, which creates a data
structure and functions for accessing various fields in it.
This can be useful, so I'm doing something similar here.
(defstruct book title author subject book-id )
~~~
{{
:make-helper (nsq-) [ d:create , ] dip does ;
:make-struct (ns-) d:create , [ here swap fetch allot ] does ;
---reveal---
:defstruct (sa-)
dup array:length
[ n:dec swap
[ 'ab 'aabab reorder
'@ s:append [ fetch + fetch ] make-helper
'! s:append [ fetch + store ] make-helper
n:dec
] array:for-each drop
] sip swap make-struct ;
}}
~~~
```
'book { 'title 'author 'subject 'book-id } defstruct
book 'A const
"The_Hobbit &A title!
"J.R.R._Tolkien &A author!
"Fantasy &A subject!
:info (a-)
[ subject@ ] [ author@ ] [ title@ ] tri
'%s_by_%s_is_a_%s_book. s:format s:put nl ;
&A info
```