1

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!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Kevin Cruz
  • 37
  • 5

1 Answers1

2

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

CapelliC
  • 59,646
  • 5
  • 47
  • 90
  • 2
    Yep, stupid fix indeed, I've been looking at code for so long that I was intent on putting it all into one predicate as opposed to splitting it up. Thanks CapelliC, great answer! `nat(0).` `nat(X) :- nat(Y), X is Y+1.` `sq(X) :- nat(Y), X is Y*Y.` – Kevin Cruz Jun 04 '13 at 06:25