1

I am a total novice to Prolog and still am getting used to its logic.

I have a task to create functions that turn a natural number into an "S-number" and vice versa.

So Number 0 would be 0.
Number 1 would be s(0).
Number 2 would be s(s(0)).
And so on.

nat(0).
nat(s(0)):- nat(X).

The function for finding a natural number for a given S-number I already have:

s2nat(0, 0) :- !.
s2nat(s(S),Number) :- s2nat(S,NewNumber), Number is NewNumber + 1.

So ?- s2nat(s(s(s(0))), X) would give X=3 as an output.

Now I need to write a function that does the opposite: returns an S-number for a given natural number.

And here I am stuck. I don't quite understand how to write a condition so that Prolog understands that I need s(S) to be returned. The condition Number is NewNumber + 1 doesn't work anymore to go back and get to a "0".

Do you have any advice?

false
  • 10,264
  • 13
  • 101
  • 209

1 Answers1

1

In the recursive step, you can check if Number > 0, and peform recursion with Number-1:

snat(0, 0).
snat(s(S), Number) :-
    Number > 0,
    Number1 is Number-1,
    s2nat(S, Number1).

We can make the predicate multidirection, for example by using the clpfd library:

:- use_module(library(clpfd)).

snat(0, 0).
snat(s(X), N) :-
    N #> 0,
    N1 #= N-1,
    snat(X, N1).

This predicate can thus calculate the Peano representation of a number, calculate the number the Peano representation represents, validate if the given Peano number is indeed the given number, and enumerate over all possible Peano representations and their corresponding number:

?- snat(X, 4).
X = s(s(s(s(0)))) ;
false.

?- snat(s(s(0)), N).
N = 2.

?- snat(s(s(0)), 2).
true.

?- snat(s(s(0)), 4).
false.

?- snat(X, N).
X = N, N = 0 ;
X = s(0),
N = 1 ;
X = s(s(0)),
N = 2 ;
X = s(s(s(0))),
N = 3 ;
X = s(s(s(s(0)))),
N = 4 
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • thank you very much! My mistake was with ```Number1 is Number-1``` . I was stupidly trying to put it in the end as the first time. Thanks a lot, in the beginning it definitely helps to get a punch from the side. – Wonderaleks Apr 10 '20 at 18:17