C language CPS implementation of Fibonacci sequence example

  • 2020-04-02 02:15:26
  • OfStack

CPS:http://en.wikipedia.org/wiki/Continuation-passing_style
The sample code USES iteration + tail recursion.


#include <stdio.h>
typedef void (*END_OF_END)(unsigned long);
void fibonacci(int, unsigned long, unsigned long, void(*)(unsigned long));
void
notify(unsigned long res) {
  printf("Ultimate result: %lun" res);
  exit(0);
}

void
fibonacci(int n, unsigned long v1, unsigned long v2, void(*notify)(unsigned long)) {
  if (n <= 0) notify(v2);
  fibonacci(n - 1, v2, v1 + v2, notify);
}
int
main(void) {
  fibonacci(100 - 2, 1, 1, notify);
  return 0;
}


Related articles: