I want to implement a generic mapping function in C, although it doesn't have to be all that generic to start with.
Like Haskells simple definition of map;
map _ [] = []
map f (x:xs) = f x : map f xs
where "map double [1, 2, 3, 4] = [2, 4, 6, 8]" or "map (\x -> x / 2) [10, 20, 30] = [5, 10, 15]" etc..
I've so far done a stupid proof of concept thing for my own amusement similar to;
add f x y = f x + f y
which looks like this in C:
int square(int n) { return n*n; } int add(int f(int), int x, int y) { return f(x) + f(y); } int main() { int n = add(*square, 12, 3); // just square without the asterisk also works (as does putting & before it) printf("%d\n", n); }
Which prints the true value of 153.
Now, C and lists.. Never settled with me. I want to apply f to the head of the list and recursively call map with f and the tail of the list, till it's empty. How? How do I check that the list is empty, and how do I "cut off" an element from an existing list? Plus I need to concatenate the result from one iteration with the list that is going to constitute my result. Which way is the cleanest?