[REBOL] Generic Block to Object solution
From: al::bri::xtra::co::nz at: 8-Dec-2000 19:43
Earlier, I wrote:
> Deck: make block! divide length? Cards 3
> foreach [Type Value Number] Cards [
> insert tail Deck make object! reduce [
> 'Type: Type
> 'Value: Value
> 'Number: Number
> ]
> ]
That doesn't work. :-( I should test my code first, before misleading
people.
A generic solution to reading a block of values and creating a block of
objects is this:
[
Rebol []
Cards: [
[Type Value Number]
Gold 0 2
Gold 11 1
Cups 2 4
]
Make-Objects: function [
Table [block!] Prototype! [object!]
][
Prefix Specification Custom Make-Object
][
Prefix: "-_Make-Objects_-"
Specification: map first table func [Word [word!]] [
to word! join Prefix Word
]
Custom: map first Table func [Word [word!]] [
reduce [
to set-word! Word to word! join Prefix Word
]
]
Make-Object: function Specification [Object] [
Object: make Prototype! bind Custom 'Object
]
map next Table :Make-Object
]
Prototype: make object! [
f: function [test] [block] [
block: [] ; Don't do this at home!
append block test
probe block
]
Type: lit-word!
Value: integer!
Number: integer!
]
probe Deck: Make-Objects Cards Prototype
halt
]
And here's the result in Rebol console:
[
make object! [
f: func [test /local block][
block: []
append block test
probe block
]
Type: 'Gold
Value: 0
Number: 2
]
make object! [
f: func [test /local block][
block: []
append block test
probe block
]
Type: 'Gold
Value: 11
Number: 1
]
make object! [
f: func [test /local block][
block: []
append block test
probe block
]
Type: 'Cups
Value: 2
Number: 4
]]
There's one problem with the above code that I think is bad:
Make-Object: function Specification [Object] [
Object: make Prototype! bind Custom 'Object
]
Note that I 'bind Custom to 'Object. This is analogous to 'bind with
'self in objects.
Does anyone know of a better way to do this?
Andrew Martin
ICQ: 26227169 http://members.nbci.com/AndrewMartin/