Skip to content

Instantly share code, notes, and snippets.

@7etsuo
Created September 8, 2024 09:43
Show Gist options
  • Save 7etsuo/047593be10cccaeb0426c7dc89290d67 to your computer and use it in GitHub Desktop.
Save 7etsuo/047593be10cccaeb0426c7dc89290d67 to your computer and use it in GitHub Desktop.
lambdas in C
/** Lambdas in C. Compile with GCC!
* ███ ▄████████ ███ ▄████████ ███ █▄ ▄██████▄
*▀█████████▄ ███ ███ ▀█████████▄ ███ ███ ███ ███ ███ ███
* ▀███▀▀██ ███ █▀ ▀███▀▀██ ███ █▀ ███ ███ ███ ███
* ███ ▀ ▄███▄▄▄ ███ ▀ ███ ███ ███ ███ ███
* ███ ▀▀███▀▀▀ ███ ▀███████████ ███ ███ ███ ███
* ███ ███ █▄ ███ ███ ███ ███ ███ ███
* ███ ███ ███ ███ ▄█ ███ ███ ███ ███ ███
* ▄████▀ ██████████ ▄████▀ ▄████████▀ ████████▀ ▀██████▀
*
* https://www.x.com/7etsuo
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int multiplier;
int offset;
} context_t;
typedef struct
{
int (*func) (int, void *);
void *context;
} lambda_t;
#define lambda(return_type, context_type, context_ptr, body) \
({ \
return_type __fn__ (int x, void *context) body lambda_t l \
= {.func = __fn__, \
.context = (void *) context_ptr }; \
l; \
})
int *
map (int *arr, int size, lambda_t lambda_func)
{
int *result = malloc (size * sizeof (int));
if (result == NULL)
{
fprintf (stderr, "malloc() \n");
return NULL;
}
for (int i = 0; i < size; i++)
result[i] = lambda_func.func (arr[i], lambda_func.context);
return result;
}
int
main (int argc, char **arv)
{
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof (arr) / sizeof (arr[0]);
context_t context = {.multiplier = 3, .offset = 2};
lambda_t multiplier_with_offset = lambda (int, context_t, &context, {
context_t *ctx = (context_t *) context;
return (x * ctx->multiplier) + ctx->offset;
});
int *modified = map (arr, size, multiplier_with_offset);
if (modified == NULL)
return EXIT_FAILURE;
printf ("Modified: ");
for (int i = 0; i < size; i++)
printf ("%d ", modified[i]);
free (modified);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment