Question

I'm new to prolog I'm trying to write a predicate which counts the following: the predicates name is s2int when given:

  • s2int(0,Y) it shoud "return" Y=0.
  • s2int(s(0),Y) => Y=1.
  • s2int(s(s(0)),Y) => Y=2.
  • s2int(S(s(s(0))),Y) => Y=3.

and so on.. here is what i tried to write(very poorly), at first i tried this code:

s2intAux(0,Y).
s2intAux(X,Y):- X = s(Z) ,Y1 is Y+1, s2intAux(Z,Y1).

but whenever i try to run it by typing s2intAux(s(0),Y) i get an error saying :"ERROR: is/2: Arguments are not sufficiently instantiated" i get that error well because Y is undefined. then i tried this one:

s2intAux(0,Y).
s2intAux(X,Y):- X = s(Z) ,Y1 is Y+1, s2intAux(Z,Y1).

s2int(X,Y):- Y1 is 0, s2intA(X,Y1).

(i tried to start Y with the value zero but this one didn't work at all) I've been stuck for a couple of hours now which is why I'm turning to you guys, please help! thank you.

Was it helpful?

Solution

You need the following to resolve the most trivial case:

s2intAux(0,0).

This will cause s2intAux(0,Y) to be true when Y is instantiated to 0.

In your subsequent lines, you don't have a statement that resolves Z to 0 when you run out of the s(.). For that, you need to take care of the single s(0) case. Then you can do the general case:

s2intAux(X,Y) :- X = s(0), Y is 1.
s2intAux(X,Y) :- X = s(Z), s2intAux(Z,Y1), Y is Y1 + 1.

Note that on the general case, we have to traverse down to get to the Y is 1 before we can unravel back up and finally assign Y to Y1 + 1.

You can also write that first line as just:

s2intAux(s(0),Y) :- Y is 1.

Final answer looks like this:

s2intAux(0,0).
s2intAux(s(0),Y) :- Y is 1.
s2intAux(X,Y) :- X = s(Z), s2intAux(Z,Y1), Y is Y1 + 1.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top