Question

My code below is meant to generate the square of natural numbers in order

(i.e sq(X). -> X=0; X=1; X=4; X=9; X=16; ...)

nat(0).
nat(X) :- nat(Y), Z is Y+1, X is Z*Z.

but the answer I am getting is:

1

0 ?- nat(X).

X = 0 ;

X = 1 ;

X = 4 ;

X = 25 ;

X = 676 

Should be a quick fix, but I've spent longer on this than I'd like to say. Any help is greatly appreciated!

Was it helpful?

Solution

your nat/1 really seems to return a different sequence. Should be

nat(0).
nat(X) :- nat(Y), X is Y+1.

and then, a different predicate for square

sq(X) :- % call nat/1, square it...

please complete the code

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top