Skip to content

Instantly share code, notes, and snippets.

@CaglarGonul
Created April 11, 2013 19:55
Show Gist options
  • Save CaglarGonul/5366663 to your computer and use it in GitHub Desktop.
Save CaglarGonul/5366663 to your computer and use it in GitHub Desktop.
From Dan Grossman course. How to use closures in C.
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
typedef struct List list_t;
struct List {
void * head;
list_t * tail;
};
list_t * makelist (void * x, list_t * xs) {
list_t * ans = (list_t *)malloc(sizeof(list_t));
ans->head = x;
ans->tail = xs;
return ans;
}
list_t * map(void* (*f)(void*,void*), void* env, list_t * xs) {
if(xs==NULL)
return NULL;
return makelist(f(env,xs->head), map(f,env,xs->tail));
}
list_t * filter(bool (*f)(void*,void*), void* env, list_t * xs) {
if(xs==NULL)
return NULL;
if(f(env,xs->head))
return makelist(xs->head, filter(f,env,xs->tail));
return filter(f,env,xs->tail);
}
int length(list_t* xs) {
int ans = 0;
while(xs != NULL) {
++ans;
xs = xs->tail;
}
return ans;
}
void* doubleInt(void* ignore, void* i) { // type casts to match what map expects
return (void*)(((intptr_t)i)*2);
}
list_t * doubleAll(list_t * xs) { // assumes list holds intptr_t fields
return map(doubleInt, NULL, xs);
}
bool isN(void* n, void* i) { // type casts to match what filter expects
return ((intptr_t)n)==((intptr_t)i);
}
int countNs(list_t * xs, intptr_t n) { // assumes list hold intptr_t fields
return length(filter(isN, (void*)n, xs));
}
void printList(list_t * xs){
while(xs != NULL){
printf("%lu\n",((intptr_t)xs->head));
xs = xs->tail;
}
}
int main() {
list_t *x1 = makelist((void *)1,NULL);
list_t *x2 = makelist((void *)2,x1);
printList(x2);
list_t * x3 = doubleAll(x2);
printList(x3);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment