[REBOL] set-if
From: anton::wilddsl::net::au at: 15-Apr-2007 20:27
I am sure this issue came up before, but I didn't do much about it.
This idiom aggravates me and I don't want to write it any more,
because of the repetition:
climber: self while [climber/parent][climber: climber/parent]
Instead I want to write this:
climber: self while [set-if 'climber climber/parent][]
which only sets climber *if* there is a following value (ie. not none?
climber/parent)
and introduces a new function "set-if".
Implementation:
Simple version:
set-if: func [word value][if value [set word value] get value]
More complex version, also handling "hot" values like functions:
set-if: func [word value][if get/any 'value [set/any word get/any 'value]
get/any 'value]
Test:
; First, make a hierarchy of 3 objects, top-level, its child, and its
grandchild ("bottom").
top-level: context [
parent: none
child: none
spawn: does [
child: make self compose [
parent: (self)
child: none
]
]
]
top-level/spawn
top-level/child/spawn
bottom: top-level/child/child/spawn
; Now set the climber at the bottom and make him climb:
climber: bottom while [set-if 'climber climber/parent][]
same? climber top-level ; == true
Regards,
Anton.