A'mer Mograbi
A'mer Mograbi

Reputation: 37

Basic PROLOG counting

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

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.

Upvotes: 3

Views: 166

Answers (1)

lurker
lurker

Reputation: 58224

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.

Upvotes: 2

Related Questions