Created
March 24, 2018 05:31
-
-
Save luizperes/42788556b0c9132ca07033c1d082a996 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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