[REBOL] Re: Language shoot-out
From: lmecir:mbox:vol:cz at: 8-Nov-2001 21:37
Hi Gregg,
the NAMED-ARGS function is a nice idea, although I would suggest a slightly
different design:
named-args: function [
f[any-function!]
args[block!]
] [o stmt fa] [
o: make object! args
stmt: make block! (2 * nargs :f) + 2
insert tail stmt reduce ['return :f]
fa: first :f
repeat i nargs :f [
insert/only tail stmt 'get/any
insert tail stmt to lit-word! pick fa i
]
do bind stmt in o 'self
]
a: [1 2 3 4 5]
named-args :length? [series: a]
named-args :append [value: 1 series: a]
named-args :find [value: 3 series: a]
named-args :remove [series: a]
Gregg wrote: <<
Hi Jason,
<< dicts and named arguments [Wish REBOL had these] >>
I started playing around with both ideas, but haven't tested them
thoroughly.
; Keys don't *have* to be strings, do they?
; If you assign a block to _data, it's up to you to make it a hash! if you
want.
dictionary: make object! [
; Odd items are keys, even items are values. I.e.
; [key1 value1 key2 value2...]
_data: make hash! 50
clear: does [_data: make hash! 50]
count: does [return (system/words/length? _data) / 2]
length?: :count
empty?: does [return count = 0]
keys: does [extract head _data 2]
values: does [extract next head _data 2]
item: func [key] [
if has-key? key [return first next find/skip _data key 2]
]
has-key?: func [key] [
return found? find/skip _data key 2
]
remove: func [key] [
if has-key? key [system/words/remove/part find/skip _data key 2 2]
]
change: func [key value /only] [
either has-key? key [
either only [
system/words/change/only next find/skip _data key 2 :value
][
system/words/change next find/skip _data key 2 :value
]
][
either only [
append/only _data reduce [key :value]
][
append _data reduce [key :value]
]
]
]
contains?: func [value /only] [
either only [
return found? find/skip/only next _data value 2
][
return found? find/skip next _data value 2
]
]
]
; nargs by Ladislav Mecir and Carl Sassenrath
nargs: func [
{The number of the function arguments}
f [any-function!]
] [
-1 + index? any [find first :f refinement! tail first :f]
]
do-fn-named-args: func [fn[action! function!] args[block!] /local arg
fn-args f] [
fn-args: array nargs :fn
foreach arg args [
either (type? (second arg)) = word! [
change/part/only (at fn-args index? (find first :fn (to-word
first arg))) (get second arg) 1
][
change/part/only (at fn-args index? (find first :fn (to-word
first arg))) (second arg) 1
]
]
do head insert fn-args :fn
]
a: [1 2 3 4 5]
do-fn-named-args :length? [['series a]]
do-fn-named-args :append [['value 1] ['series a]]
do-fn-named-args :find [['value 3] ['series a]]
do-fn-named-args :remove [['series a]]
--Gregg