www.delorie.com/gnu/docs/libobjects/libobjects_26.html   search  
 
Buy GNU books!


User's Guide to the GNU Objective-C Class Library

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

12.5 Defining Functions In Place with LAMBDA()

NOTE: The LAMBDA macro does not work on all systems. We are waiting for a general fix. You should avoid using it until then.

There may not already be a function that does the operation you want performed during an enumeration. In this case you will have to write such a function yourself.

If the function will be used more than once, you should write it as C functions are usually defined. However, if the function will only be used for this one enumeration and the function is small, using the LAMBDA macro may be easier and more clear.

Macro: LAMBDA(RETTYPE, ARGS, BODY)
LAMBDA is a macro for defining a nested function and returning a pointer to that function. You can use LAMBDA wherever a function pointer is required. RETTYPE is the C type returned by the function. ARGS is the parenthesis-enclosed list of arguments to the function. (Declare them just like in an ANSI function definition.) BODY is the curly-bracket-enclosed body of the function.

For example, you could create a pointer to a function that adds its arguments like this:
 
LAMBDA(int, (int a, int b), {return a + b;})

LAMBDA is particularly convenient for enumeration methods because the macro can be placed in the position of the method argument. For instance, you can write:
 
  - fooMethod
  {
    id newColl;
    ...
    newColl = [self emptyCopyAs:[Array class]];
    [self withObjectsCall:
          LAMBDA(void, (id o), {[newColl addObject:[o copy]];})];
    return self;
  }
instead of writing:
 
  - fooMethod
  {
    id newColl = [self emptyCopyAs:[Array class]];
    void myTmpFunc(id o)
      {
        [newColl addObject:[o copy]];
      }
    ...
    [self withObjectsCall:myTmpFunc];
    return self;
  }
In these examples, there may be many lines of code between the declarations at the top of the method and the withObjectsCall: at the bottom of the method. Using LAMBDA allows you to declare the function where it is used, instead of arbitrarily far from where it is used.

The name LAMBDA comes from lambda calculus and LISP.

The LAMBDA macro and some similar macros are defined in `coll/collstd.h'.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster   donations   bookstore     delorie software   privacy  
  Copyright © 2003   by The Free Software Foundation     Updated Jun 2003