Range Over Iterators in C

#include <stdio.h>

// The List structure represents a singly-linked list
struct List {
    struct Element* head;
    struct Element* tail;
};

// The Element structure represents a node in the list
struct Element {
    struct Element* next;
    int val;
};

// Push adds a new element to the end of the list
void Push(struct List* lst, int v) {
    struct Element* newElement = malloc(sizeof(struct Element));
    newElement->val = v;
    newElement->next = NULL;

    if (lst->tail == NULL) {
        lst->head = newElement;
        lst->tail = newElement;
    } else {
        lst->tail->next = newElement;
        lst->tail = newElement;
    }
}

// PrintAll prints all elements in the list
void PrintAll(struct List* lst) {
    struct Element* current = lst->head;
    while (current != NULL) {
        printf("%d\n", current->val);
        current = current->next;
    }
}

// genFib generates Fibonacci numbers
void genFib(int limit) {
    int a = 1, b = 1;
    while (a < limit) {
        printf("%d\n", a);
        int temp = a;
        a = b;
        b = temp + b;
    }
}

int main() {
    struct List lst = {NULL, NULL};
    Push(&lst, 10);
    Push(&lst, 13);
    Push(&lst, 23);

    PrintAll(&lst);

    printf("all: [");
    struct Element* current = lst.head;
    while (current != NULL) {
        printf("%d", current->val);
        if (current->next != NULL) {
            printf(" ");
        }
        current = current->next;
    }
    printf("]\n");

    genFib(10);

    return 0;
}

This C code implements a similar functionality to the Go example, with some adaptations due to language differences:

  1. We define a List structure and an Element structure to represent our linked list.

  2. The Push function adds new elements to the end of the list.

  3. Instead of using an iterator, we implement a PrintAll function to print all elements in the list.

  4. The genFib function generates Fibonacci numbers up to a given limit.

  5. In the main function, we create a list, add elements to it, print all elements, and then generate Fibonacci numbers.

Note that C doesn’t have built-in support for generics or iterators like Go does. We’ve implemented the list for integers only, and used traditional looping constructs instead of iterators.

To compile and run this program:

$ gcc -o list_example list_example.c
$ ./list_example
10
13
23
all: [10 13 23]
1
1
2
3
5
8

This C implementation provides similar functionality to the Go example, demonstrating linked list operations and Fibonacci number generation. However, it lacks the advanced features like generics and iterators that are available in Go.