#include <stdio.h>
#include <stdlib.h>

struct item {
    int val;
    struct item *next;
};

typedef int (*intfunptr)(int, int);

/* the two recursive versions from the book */
int intlist_reduce_l(intfunptr f, int i, struct item *ls)
{
    return ls ? intlist_reduce_l(f, f(i, ls->val), ls->next) : i;
}

int intlist_reduce_r(intfunptr f, int i, struct item *ls)
{
    return ls ? f(ls->val, intlist_reduce_r(f, i, ls->next)) : i;
}

/* left reduction as a loop: i holds the result so far */
int intlist_reduce_l_loop(intfunptr f, int i, struct item *ls)
{
    for (; ls; ls = ls->next)
        i = f(i, ls->val);
    return i;
}

/* right reduction as a loop: possible for an array, walked backwards */
int intarray_reduce_r_loop(intfunptr f, int i, const int *arr, int len)
{
    int k;
    for (k = len - 1; k >= 0; k--)
        i = f(arr[k], i);
    return i;
}

void push(struct item **ls, int val)
{
    struct item *tmp = malloc(sizeof(*tmp));
    tmp->val = val;
    tmp->next = *ls;
    *ls = tmp;
}

void pop(struct item **ls)
{
    struct item *tmp = *ls;
    *ls = (*ls)->next;
    free(tmp);
}

/* ... and for a list only through a reversed copy */
int intlist_reduce_r_loop(intfunptr f, int i, struct item *ls)
{
    struct item *rev = NULL;
    for (; ls; ls = ls->next)
        push(&rev, ls->val);

    while (rev) {
        i = f(rev->val, i);
        pop(&rev);
    }
    return i;
}

struct item *make_list(const int *arr, int len)
{
    struct item *first = NULL;
    int k;
    for (k = len - 1; k >= 0; k--)
        push(&first, arr[k]);
    return first;
}

int sub(int x, int y) { return x - y; }

int main()
{
    int arr[] = { 1, 2, 3, 4 };
    struct item *ls = make_list(arr, 4), *tmp;
    printf("left,  recursion: %d\n", intlist_reduce_l(sub, 0, ls));
    printf("left,  loop:      %d\n", intlist_reduce_l_loop(sub, 0, ls));
    printf("right, recursion: %d\n", intlist_reduce_r(sub, 0, ls));
    printf("right, array:     %d\n", intarray_reduce_r_loop(sub, 0, arr, 4));
    printf("right, list:      %d\n", intlist_reduce_r_loop(sub, 0, ls));
    while (ls) {
        tmp = ls;
        ls = ls->next;
        free(tmp);
    }
    return 0;
}
