I need to write a recursive predicate rectangle
, such that rectangle(M, N)
writes out a solid rectangle of size M x N
of asterisks, i.e., there should be M
rows and N
columns in the rectangle. For example:
?- rectangle(3,8).
********
********
********
true
So far I have the statement line
that prints N
asterisks on a line:
line(0).
line(N) :- write('*'), A is N-1 , line(A).
I've tried everything, but I keep getting an infinite grid of asterisks. Here's what I've got so far:
rectangle(0,0).
rectangle(M,N) :-
line(M),
write('*'), nl, A is N-1, line(A-1),
rectangle(M,A).
I know your assignment requires a recursive procedure, then you should not consider this as an answer. But I'd like to show a possible concise solution, using a metapredicate:
Not every Prolog support calling a variable. In my old Prolog interpreter, for instance, I'd write
loop_n(P, N) :- forall(between(1, N, _), call(P)).
Getting an infinite grid of asterisks is because you haven't defined rectangle(M,0). So, the code should be as follows: