So:
--------------------------------------------------
(defun fact (x)
(if (< x 1)
1
(* x (fact (1- x)))))
(defun main ()
(format t "~A~%" (fact 100)))
--------------------------------------------------
would translate to:
--------------------------------------------------
#include <stdio.h>
int fact(int x){
if(x<1){
return(1);
}else{
return(x*fact(x-1));
}
}
int main(void){
printf("%d\n",fact(100));
return(0);
}
--------------------------------------------------
Oops, already you have to use a library, C doesn't have I/O built-in.
Let's just ignore that:
============================================================
Running the C program:
============================================================
./c_fact
0
============================================================
Running the Lisp program:
============================================================
./fact
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
============================================================
To get the same result in C, you need to use yet another library, mpz,
and then the code is not maintainable anymore:
--------------------------------------------------
#include <stdio.h>
#include <gmp.h>
mpz_t one;
void fact(mpz_ptr r,mpz_srcptr x){
if(mpz_cmp(x,one)<0){
mpz_set(r,one);
}else{
mpz_t rr;
mpz_t x_minus_1;
mpz_init(rr);
mpz_init(x_minus_1);
mpz_sub(x_minus_1,x,one);
fact(rr,x_minus_1);
mpz_mul(r,rr,x);
mpz_clear(rr);
mpz_clear(x_minus_1);
}
}
int main(void){
mpz_t r;
mpz_t arg;
mpz_init(one);
mpz_set_ui(one,1);
mpz_init(r);
mpz_init(arg);
mpz_set_ui(arg,100);
fact(r,arg);
gmp_fprintf(stdout,"%Zd\n",r);
mpz_clear(r);
mpz_clear(arg);
return(0);
}
--------------------------------------------------
============================================================
Running the C program with mpz:
============================================================
./mpz_fact
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
And this is just for *; there are 977 other symbols in CL…
--
__Pascal Bourguignon__
http://www.informatimago.com/
A bad day in () is better than a good day in {}.