I am trying to write a generic Search function on a linked list in C. The function is as follows:
void* get_when_true(linked_list *l,
int (*condition)(const void*)) {
node **walk = &l->head;
while (*walk != NULL && !condition((*walk)->data)) {
walk = &((*walk)->next);
}
return (*walk)->data;
}
Basically condition is a function pointer to a function which will be tested against each element of linked list and whenever this function returns true that particular node will be returned.
Each of the node in my linked list stores some ID. My problem is if I wan't to search for a specific ID I have to write a separate search function which can only check for that particular ID. Basically if I wan't to look for ID 10. I have to write a function
int isID_10(const void *a) {
// cast A to appropriate poitner
return a->ID == 10;
}
If I want to test for some other ID say 30, I will have to write a different function again..I think you got my point.
I can only think of currying to solve this problem..but unfortunately C doesn't provide currying and I can't use some compiler specific work arounds because my code should compile on all platforms.
Using global variable for the search ID is one solution but I wan't to avoid it.
How to solve this problem?