I have not tested this but it should work:
term2int(0,0).
term2int(s(T),N) :- term2int(T,N1), N is N1+1.
term2int(p(T),N) :- term2int(T,N1), N is N1-1.
No need to check if > 0 or otherwise, just use s
and p
for that case. Also N
works as a counter.