Generating Fibonacci Numbers

Prolog and foreign languages are generally intercallable in Quintus Prolog; in particular, arbitrarily nested calling is permitted. The following example uses recursive calling between Prolog and C to generate Fibonacci numbers:

                                     
fib.pl
fib :- int(I), fib(I, F), write(fib(I,F)), nl, fail. int(I) :- int(0, I). int(I, I). int(I, K) :- J is I+1, int(J, K). fib(N, F) :- ( N =< 1 -> F = 1.0 ; N1 is N-1, N2 is N-2, c_fib(N1, F1), c_fib(N2, F2), F is F1+F2 ). :- extern(fib(+integer, -float)). foreign(c_fib, c_fib(+integer, [-float])). foreign_file(fib, [c_fib]). :- load_foreign_files(fib, []).
                                      
fib.c
#include <quintus/quintus.h> double c_fib(i) long int i; { float f1, f2; QP_pred_ref fib = QP_predicate("fib", 2, "user"); if (i <= 1) { return 1.0; } else { QP_query(fib, i-1, &f1); QP_query(fib, i-2, &f2); return f1+f2; } }