Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top