write a prolog program displaying an M*N grid of asterisk?

半世苍凉 提交于 2020-01-05 05:56:19

问题


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).

回答1:


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:

loop_n(P, N) :- forall(between(1, N, _), P).
rectangle(R, C) :- loop_n((loop_n(write(*), C), nl), R).

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)).




回答2:


Getting an infinite grid of asterisks is because you haven't defined rectangle(M,0). So, the code should be as follows:

rectangle(0,0).
rectangle(M,0).
rectangle(M,N) :-
    line(M),nl, A is N-1, rectangle(M,A).
line(0).
line(B) :- write('*'), Z is B-1 , line(Z).


来源:https://stackoverflow.com/questions/15313626/write-a-prolog-program-displaying-an-mn-grid-of-asterisk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!