[DGD] How to make a more powerful function call?
Mikael Lind
z94lind at mtek.chalmers.se
Thu Aug 9 11:21:09 CEST 2001
Quoting myself from 18:34, 2001-08-08:
> Quoting Brandon Rush from 21:56, 2001-08-07:
>
> > [...]
> >
> > I was talking to another coder (not using DGD) who was telling me about
> > a foreach() kfun/efun. It's called in a form like
> >
> > foreach( var in *array) { block of code }.
> >
> > [...]
>
> You are asking for a new kind of statement - not a kfun, efun or
> other function. There was an extended discussion on foreach earlier
> this year. Check the list archives.
Perhaps I could have been more humble and helpful. Even without
foreach, it is quite possible to avoid a lot of the (i = 0; i < size;
i++) in your code, if this is something that you want to do.
Disclaimer: The code supplied in this mail has not been tested.
When you are looping through an array, it is often because you want
to filter, map or fold it. It is trivial to implement a generic
function for each of these cases. filter_array() and map_array() are
included in many mudlibs. Some consider them elegant, som do not.
/* generic fold */
mixed fold(string func, mixed init, mixed *arr) {
int i, size;
object obj;
mixed result;
result = init;
obj = this_object();
size = sizeof(arr);
for (i = 0; i < size; i++) {
result = call_other(obj, func, result, arr[i]);
}
return result;
}
/* example of custom fold */
string join(string *arr) {
return fold("concat", "", arr);
}
/* operator for custom fold */
string concat(string left, string right) {
return left + right;
}
Warning: Do not place functions like the one above in trusted code,
as they can be used to make calls to arbitrary functions. You can for
instance add security by checking that the passed function is defined
by the calling program, or add some kind of safe prefix to the
function name.
Now that we have light-weight objects, it is also possible to
implement a collection API, including iterators.
object set, iterator;
mixed member;
set = new_object(SET);
set->add(17);
set->add(33);
set->add(42);
iterator = set->iterator();
while (iterator->has()) {
member = iterator->get();
/* ... */
}
// Mikael / Elemel
--
I embrace my desire to feel the rhythm / To feel connected enough to
step aside and weep like a widow / To feel inspired / To fathom the
power / To witness the beauty / To bathe in the fountain / To swing
on the spiral of our divinity and still be a human // Tool
_________________________________________________________________
List config page: http://list.imaginary.com/mailman/listinfo/dgd
More information about the DGD
mailing list