Skip to content

Instantly share code, notes, and snippets.

@desg
Created June 13, 2012 04:26
Show Gist options
  • Save desg/2921863 to your computer and use it in GitHub Desktop.
Save desg/2921863 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *next;
} node;
int increment(int);
int square(int);
node * map(node *l, int (*func)(int));
node * list_add(node *head, int value);
int
main()
{
node *l = NULL;
l = list_add(l, 3);
l = list_add(l, 4);
l = list_add(l, 5);
map(l, square);
return 0;
}
node *
list_add(node *head, int value)
{
if (head == NULL) {
head = malloc(sizeof(node));
head->value = value;
head->next = NULL;
} else {
node *n = head;
while (n->next != NULL)
n = n->next;
n->next = malloc(sizeof(node));
n->next->value = value;
n->next->next = NULL;
}
return head;
}
node *
map(node *head, int (*func)(int))
{
node *i = NULL;
for(node *n=head; n != NULL; n=n->next)
{
while(i != NULL)
{
list_add(i, func(n->value));
}
}
return i;
}
int
square(int n)
{
return n * n;
}
int
increment(int n)
{
return n + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment