retroforth/example/defstruct.retro
crc b63de01059 fix bug in example/defstruct that was causing the structure name to be lost when the temporal string pool rolls back to start
FossilOrigin-Name: 470ba5902441b37d35805b9ddba45ff225288d13bbf02a811c8f9522af6a6e8c
2021-12-10 11:46:41 +00:00

37 lines
916 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-)
&s:keep dip dup a:length
[ n:dec swap
[ 'ab 'aabab reorder
'@ s:append [ fetch + fetch ] make-helper
'! s:append [ fetch + store ] make-helper
n:dec
] a:for-each drop
] sip swap make-struct ;
}}
~~~
```
'book { 'title 'author 'subject 'book-id } defstruct
book 'A const
'The_Hobbit s:keep &A title!
'J.R.R._Tolkien s:keep &A author!
'Fantasy s:keep &A subject!
:info (a-)
[ subject@ ] [ author@ ] [ title@ ] tri
'%s_by_%s_is_a_%s_book. s:format s:put nl ;
&A info
```