Project Euler Problem1
C言語で関数型プログラミングの考え方でやりました
#include <stdio.h> #include <stdlib.h> struct list { int value; struct list *next; }; typedef int func_t(int); struct list *cons(int val, struct list *lst) { struct list *p; if ((p = malloc(sizeof(struct list))) == NULL) exit(EXIT_FAILURE); p->value = val; p->next = lst; return p; } struct list *enumerate(int st, int end) { if (st > end) { return NULL; } else { return cons(st, enumerate(st+1, end)); } } struct list *filter(func_t *f, struct list *lst) { if (lst == NULL) { return NULL; } else { if (f(lst->value) == 1) { return cons(lst->value, filter(f, lst->next)); } else { return filter(f, lst->next); } } } int divisible_3or5(int n) { if (n%3==0 || n%5==0) { return 1; } else { return 0; } } int sum(struct list *lst) { if (lst == NULL) { return 0; } else { return lst->value + sum(lst->next); } } void free_memory(struct list *p) { struct list *temp; while (p != NULL) { temp = p->next; free(p); p = temp; } } int main(int argc, char const *argv[]) { struct list *p, *q; p = enumerate(1, 999); q = filter(divisible_3or5, p); printf("%d\n", sum(q)); free_memory(p); free_memory(q); return 0; }