Want to use Lambda Functions in C? Lambda for C

Want to use Lambda Functions in C? Lambda for C

Some programming languages featrue Lamda Functions, that means you can call small anonymous functions. We can also use lambda in C…


Introduction

Some programming languages featrue Lamda Functions, that means you can call small anonymous functions.

“Lambda” function comes from mathematics, where it is called lambda calculus.

A lambda function can take any number of arguments, but can only have one expression. Why Use Lambda Functions? The power of lambda is better shown when you use them as an anonymous function inside another function.

For example, in Python, Lambda Functions is supported.

A simple function expressed with a standard Python function definition using the keyword def as follows:

def add(x):
    return x+1

In contrast, we can use Lambda:

lambda x: x+1
  • Keyword: lambda
  • Bound variable: x
  • Body: x+1

Modern C++ also has lambda expressions:

[ capture clause ] (parameters) -> return-type  
{   
   definition of method   
} 

Lambda & C

In C, lambda is not naturely supported, so you have to define a function by name and pass a pointer. However, it’s not a big problem — if you use gcc, there are some nonstandard features you can use to get what you want out of the lambda functions.

So let’s see how it works.

#define lambda(lambda$_ret, lambda$_args, lambda$_body)\
({\
lambda$_ret lambda$__anon$ lambda$_args\
lambda$_body\
&lambda$__anon$;\
})

This takes advantage of the gcc and the fact that gcc will let you use dollar signs in identifiers. You meed to pass --std=gnu99 on the gcc command line to make this work properly, for example:

$ gcc -o lambda --std=gnu99 lambda.c

Here’s a full example:

#include <stdio.h>

#define lambda(lambda$_ret, lambda$_args, lambda$_body)\
  ({\
    lambda$_ret lambda$__anon$ lambda$_args\
      lambda$_body\
    &lambda$__anon$;\
  })

int main(int argc, char *argv[])
{
    printf( "Sum = %d\n", lambda( int, (int x, int y){ return x + y; })(1, 2) );
    return 0;
}

Result:

Sum = 3

Conclusion

In fact, you really don’t have to have lambda with C. they are not very portable. If lambda was a useful feature K&R would have included it. Just for fun.


© 2020-2021. All rights reserved.