Skip to content

Instantly share code, notes, and snippets.

@zoedsoupe
Created October 11, 2024 11:02
Show Gist options
  • Save zoedsoupe/2dff082e6e47db962097d758662dae20 to your computer and use it in GitHub Desktop.
Save zoedsoupe/2dff082e6e47db962097d758662dae20 to your computer and use it in GitHub Desktop.
higher order function in pure C
/*
WE WANT THAT:
true = λx.λy.x
false = λx.λy.y
not = λx.x false true
and = λx.λy.x y false
or = λx.λy.x true y
*/
#include <stdio.h>
#include <stdlib.h>
// Define the boolean function type
typedef void* (*bool)(void* x, void* y);
// Define 'true' and 'false' functions
void* true_fn(void* x, void* y) {
return x;
}
void* false_fn(void* x, void* y) {
return y;
}
// Define 'not' function
bool not_fn(bool x) {
return (bool)x(false_fn, true_fn);
}
// Define 'and' function
bool and_fn(bool x, bool y) {
return (bool)x(y, false_fn);
}
// Define 'or' function
bool or_fn(bool x, bool y) {
return (bool)x(true_fn, y);
}
// Functions to represent boolean values as strings for testing
const char* true_str() {
return "true";
}
const char* false_str() {
return "false";
}
// Function to get the string representation of a boolean
const char* to_string(bool b) {
return (const char*)b((void*)true_str(), (void*)false_str());
}
int main() {
// Define the boolean values
bool t = true_fn;
bool f = false_fn;
// Array of booleans for iteration
bool bools[] = { t, f };
const char* bool_names[] = { "true", "false" };
// Print truth table for NOT
printf("Truth table for NOT:\n");
for (int i = 0; i < 2; i++) {
bool a = bools[i];
printf("NOT %s: %s\n", to_string(a), to_string(not_fn(a)));
}
printf("\n");
// Print truth table for AND
printf("Truth table for AND:\n");
for (int i = 0; i < 2; i++) {
bool a = bools[i];
for (int j = 0; j < 2; j++) {
bool b = bools[j];
printf("%s AND %s: %s\n", to_string(a), to_string(b), to_string(and_fn(a, b)));
}
}
printf("\n");
// Print truth table for OR
printf("Truth table for OR:\n");
for (int i = 0; i < 2; i++) {
bool a = bools[i];
for (int j = 0; j < 2; j++) {
bool b = bools[j];
printf("%s OR %s: %s\n", to_string(a), to_string(b), to_string(or_fn(a, b)));
}
}
return 0;
}
#include <stdio.h>
typedef int (*FoldFunc)(int acc, int elem);
int foldl(int *arr, int acc, FoldFunc f, size_t len) {
for (int i = 0; i < len; i++) {
acc = f(acc, arr[i]);
}
return acc;
}
int add(int a, int b) {
return a + b;
}
int main() {
puts("i'm about to do something blasmefemous...\n");
int arr[] = {1, 2, 3, 4, 5};
puts("we have a simple array, why not to use HOF?\n");
size_t len = sizeof(arr) / sizeof(arr[0]);
int sum = foldl(arr, 0, add, len);
printf("Sum: %d\n", sum);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment