[<<][c][>>][..]
Fri Nov 28 12:11:49 CET 2008

Iterators vs. Fold vs. Comprehensions

http://lambda-the-ultimate.org/node/1224

What you want in C however, is a comprehension instead of a fold: this
allows to use lexical variables without creating explicit iteratee
context objects, or using gcc's downward closures.

A comprehension is really just the macro form of a fold: the iteratee
is inlined.

The problem with comprehension macros is the maintenance of state
across the loop body.  Such a macro looks like:

  type1 var1;
  type2 var2;
  ...
  FOR_COLLECTION(var1, var2, ...) {
      // code that uses var1, var2, ...
  }

Without access to the scope of the FOR and an intermediate scope of
the loop body, this becomes quite difficult to hack..  Something like
this might work better:

  type1 var1;
  type2 var2;
  ...
  FOR_COLLECTION(var1, var2, ...) 
      // code that uses var1, var2, ...
  END_FOR

In short, it's too complicated to do in general, so let's stick to
generic folds.


EDIT: Actually it is not necessary to store iteration state variables
inside the context.  Using a macro like this:

#define DE_COLLECTION_FOR_(_list, _de, _del)            \
    struct list *_del;                                  \
    for(_del = (*_list), _de = _del ? _del->de : NULL;  \
        _de;                                            \
        _del = _del->next, _de = _del ? _del->de : NULL)
#define DE_COLLECTION_FOR(list, de) DE_COLLECTION_FOR_(list, de, __del__)

The iteration state is stored outside the context.  The compiler will
probably optimize the use of the variable, so we need not worry about
memory usage.  The only remaining problem is the "__del__" symbol: it
is generated inside the macro and might cause name clashes.

How to implement gensym in C?[1]

[1] entry://20100825-142132





[Reply][About]
[<<][c][>>][..]