how to turn a number from the unit form into an integer in prolog?

197 views Asked by At

I have his code in prolog:

int2term(0,0).
int2term(N,s(T)) :- N>0, M is N-1, int2term(M,T).
int2term(N,p(T)) :- N<0, M is N+1, int2term(M,T).

that shows a number from this form s(s(0)) to this form 2 . I tried to make the reversed version specically 2 -> s(s(0)) using this but nothing :

term2int(0,0).
term2int(N,T) :- N>0, M is N-1, term2int(M,s(T)).

Any suggestions ?

2

There are 2 answers

1
sersdyh On BEST ANSWER

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.

0
lurker On

This is a slightly different version which is tail recursive and avoids some of the infinite recursion cases (e.g., try term2int(T, 2). and press ; after the first solution):

term2int(0, 0).
term2int(s(X), Y) :-
    term2int(s(X), 0, Y).
term2int(p(X), Y) :-
    term2int(p(X), 0, Y).

term2int(0, Y, Y) :- !.
term2int(s(X), A, Y) :-
    (integer(Y) -> Y > 0 ; true),
    A1 is A+1,
    term2int(X, A1, Y).
term2int(p(X), A, Y) :-
    (integer(Y) -> Y < 0 ; true),
    A1 is A-1,
    term2int(X, A1, Y).