Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making use of an object's fields implicit in a block of code

Tags:

rebol

rebol3

Let's say I have:

 foo: object [bar: 10]

 print foo/bar ;-- output 10

Is there some xxx for saying:

 foo: object [bar: 10]

 xxx foo [
     print bar ;-- output 10
 ]

Binding will work, but is ugly (puts object reference after the block) and you have to call DO:

 foo: object [bar: 10]

 do bind [
     print bar ;-- output 10
 ] foo

(It also mutates the block parameter by default...which is probably not a good general property for the sought-after xxx.)

USE would seem like a good word for xxx, but it is taken for something else already: it lets you declare words inside a local context while leaving the previous definitions of that word alone:

 foo: object [bar: 10]

 use [foo] [
     foo: object [bar: 20]
     print foo/bar ;-- prints 20
 ]

 print foo/bar ;-- prints 10

Does something already do what I want in the box, or does one have to write it? WITH might be a good name, from other languages with a parallel kind of feature.

One option would be to make it an extension of use...perhaps what it did if you gave it a GET-WORD! in the list.

like image 336
HostileFork says dont trust SE Avatar asked Feb 01 '26 07:02

HostileFork says dont trust SE


1 Answers

This is one of the primary use-cases for in, the "inverted" cousin of bind:

>> foo: object [bar: 10]
== make object! [
    bar: 10
]

>> do in foo [print bar]
10

If you don't want the code block mutated, add a copy to the mix: do in foo copy [print bar].

Be sure to also check out (again) the the answer to "How to use IN with a block instead of an object?".

like image 181
earl Avatar answered Feb 03 '26 08:02

earl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!