1:- module(primrec, []).    2:- dynamic  def/2.    3:- include(op).    4
    5def(
    6   fact(0) =1; 
    7   fact(s(n)) = s(n) * fact(n);
    8    
    9   0 * x = 0;
   10   s(n)* x =  x + n * x;
   11    
   12   0 + x = x;
   13   s(n) + x  = s(n + x);
   14
   15%%% 素数判定関数用
   16
   17   decr(0) = 0;
   18   decr(s(x)) = x;
   19
   20  (m - 0) = m;
   21  (m - s(n)) = decr(m- n);
   22
   23   zero(0)=1;
   24   zero(s(x))=0;
   25
   26   not(0) = 1;
   27   not(s(n)) = 0;
   28
   29   &(0, x) = 0;
   30   &(s(n), x) = not(zero(x));
   31
   32   or(x, y) =  not(&(not(x), not(y)));
   33
   34   if(0, x, y) = y;
   35   if(s(n), x, y) = x;
   36
   37   positive(0) = 0;
   38   positive(s(x)) = 1;
   39    
   40   (x > y) = positive(x - y);
   41    
   42   (x=y) = &(zero(x-y), zero(y-x));
   43
   44   mod_aux(m, r) = if(m-r>1, r+1, 0);
   45    
   46   mod(0, m) = 0;
   47   mod(s(x), m) =  mod_aux(m, mod(x, m));
   48
   49   prime(x) = &(x>1, not(exists_proper_divisor(x, x))); 
   50    
   51   has_a_factor(0, y) = 0; 
   52   has_a_factor(s(x), y) =  &(x>1, or(mod(y,x)=0, has_a_factor(x, y))))
   52.
   53
   54
   55pr_eval(X, Y):- integer(X), !, X >= 0, int_numeral(X, Y).
   56pr_eval(T, V):- mapterm(pr_eval, T, T0), pr_apply(T0, V).
   57
   58pr_apply(X, Y):- def(X, Body), !, pr_eval(Body, Y).
   59pr_apply(X, X).
   60
   61int_numeral(0, 0):-!.
   62int_numeral(X, s(Y)) :- X1 is X-1, int_numeral(X1, Y).
   63
   64numeral_int(0, 0).
   65numeral_int(s(X), Y):- numeral_int(X, X0), Y is X0+1.
   66
   67pr(Query, V=V0):- abolish(def/2),
   68	def(Eqs), 
   69	assert_pr(def, Eqs),
   70	pr_eval(Query, V0),
   71	numeral_int(V0, V).
   72
   73pr_eval_demo(Eqs, Query, V=V0):- abolish(def/2),
   74	assert_pr(def, Eqs),
   75	pr_eval(Query, V0),
   76	numeral_int(V0, V).
   77	
   78assert_pr(D, A; B):- !, assert_pr(D, A), assert_pr(D, B).
   79assert_pr(D, A = B):- subst_var(A=B, A0=B0),
   80	C =.. [D, A0, B0],
   81	assert(C)