Search code examples
objectrebolrebol3

Interleave blocks, or make object out of two blocks (field names and values)


Instead of creating objects by writing:

obj: object [
    name: "Fork"
    id: 1020
]

I'd like to write something like...

obj: something-or-another [name id] ["Fork" 1020]

...and get the same result. An ideal solution would also permit:

obj: something-or-another [name: id:] ["Fork" 1020]

Easy enough to write a something-or-another, but does this fit something already "in the box"?


Solution

  • I don't believe there's a baked-in way to do this. Not difficult though:

    func [words values][
        set words: context append map-each word words [to set-word! word] none values
        words
    ]
    

    I suppose I could break this down a little:

    func [
        "Creates an Object From a Block of Words, Assigns Values"
        words [block!] "Words used to create object"
        values "Value(s) to assign"
    ][
        words: map-each word words [to set-word! word] ; The requisite set-words
        append words none ; Initial value for all words
        words: context words ; Create our object
        set words values ; Assigns our value(s) to the object
        words ; returns the object
    ]
    

    You might employ a different method to interleave blocks, such as:

    func [words [block!] values [block!]][
        collect [
            repeat index max length? words length? values [
                keep words/:index
                keep values/:index
            ]
        ]
    ]