1. tensorpudding
  2. toybox

Commits

Michael  committed 7779606

More list fun.

  • Participants
  • Parent commits b7f7c2a
  • Branches default

Comments (0)

Files changed (3)

File c/list/list.c

View file
   return rev;
 }
 
+float foldr(float (*fp)(float,float), float acc, node_t* list) {
+  while (list) {
+    acc = (*fp)(list->val,acc);
+    list = list->next;
+  }
+  return acc;
+}
+
+node_t* map(float (*fp)(float), node_t* list) {
+  node_t* iter = list;
+  while (iter) {
+    iter->val = (*fp)(iter->val);
+    iter = iter->next;
+  }
+  return list;
+}
+
+float head(node_t* list) {
+  if (list) {
+    return list->val;
+  } else {
+    perror("Attempted to take head of empty list!");
+    abort();
+  }
+}
+
+node_t* tail(node_t* list) {
+  if (list) {
+    return list->next;
+  } else {
+    perror("Attempted to take tail of empty list!");
+    abort();
+  }
+}
+
+node_t* filter(int (*fp)(float), node_t* list) {
+  if (list) {
+    if ((*fp)(list->val)) {
+      node_t* flist;
+      flist = list;
+      flist->next = filter(fp, list->next);
+      return flist;
+    } else {
+      return filter(fp, list->next);
+    }
+  } else {
+    return list;
+  }
+}    
+
 void print_list(node_t* head) {
   int i = 1;
-  while (head != NULL) {
+  while (head) {
     printf("Element %d is %f\n", i, head->val);
     head = head->next;
     i++;

File c/list/list.h

View file
 } node_t;
 
 node_t* reverse(node_t*);
+float foldr(float (*fp)(float,float), float, node_t*);
+node_t* map(float (*fp)(float), node_t*);
+node_t* filter(int (*fp)(float), node_t*);
+float head(node_t*);
+node_t* tail(node_t*);
 void print_list(node_t*);
+

File c/list/test.c

View file
 #include <stdio.h>
 #include "list.h"
 
+float sum(float a, float b) { return (a+b); }
+float addfive(float n) { return (5+n); }
+int isfive(float n) {
+  if (n == 10.0) {
+    return 1;
+  } else {
+    return 0;
+  }
+}
+
 int main() {
   node_t* l = malloc(sizeof(node_t));
   node_t* ltwo = malloc(sizeof(node_t));
   printf("\n");
   l = reverse(l);
   print_list(l);
+  print_list(map(&addfive, l));
+  printf("\n\n");
+  print_list(filter(&isfive, l));
+  printf("\n\n");
+  printf("The sum is: %f\n", foldr(&sum, 0, l));
   return 0;
 }