Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@luizperes
Created March 24, 2018 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luizperes/42788556b0c9132ca07033c1d082a996 to your computer and use it in GitHub Desktop.
Save luizperes/42788556b0c9132ca07033c1d082a996 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef int (*Fn) (int);
typedef struct _list {
int n;
Fn f;
} list;
int odd (int x)
{
return x*2+1;
}
int fact (int x)
{
if (x == 1 || x == 0)
return 1;
return x * fact(x - 1);
}
int head (void *l)
{
list *lst = (list *)l;
return lst->f(lst->n);
}
void* tail (void *l)
{
list *lst = (list *)l;
lst->n += 1;
return l;
}
void* build(Fn f)
{
list *lst = (list *) malloc(sizeof(list));
lst->n = 0;
lst->f = f;
return lst;
}
int trampoline(Fn f, int n)
{
void* lst = build(f);
for (int i = 0; i < n; i++) {
lst = tail(lst);
}
return head(lst);
}
int main()
{
printf("Trampoline odd value: %d\n", trampoline(&odd, 5));
printf("Factorial of 4 = %d", trampoline(&fact, 4));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment