Skip to content

Instantly share code, notes, and snippets.

@siritori
Created May 8, 2011 04:34
Show Gist options
  • Save siritori/961109 to your computer and use it in GitHub Desktop.
Save siritori/961109 to your computer and use it in GitHub Desktop.
foldl_sum.c
#include <stdlib.h>
#include <stdio.h>
typedef struct _list {
int d;
struct _list *next;
} list;
typedef int(*func)(list*, int);
list* new_list() {
list *nl = (list*)malloc(sizeof(list));
nl->d = -1;
nl->next = NULL;
return nl;
}
list* push(list* l, int i) {
list *nl = new_list();
nl->d = i;
nl->next = l;
return nl;
}
int f(list *i, int acc) {
return acc + i->d;
}
int foldl(func fun, int acc, list *l) {
return l->d == -1? acc: foldl(fun, fun(l, acc), l->next);
}
int main(int argc, char *argv[]) {
list *l = push(push(push(push(new_list(), 1), 2), 3), 4);
printf("%d\n", foldl(f, 0, l));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment