编写一个显示 M*N 星号网格的序言程序? [英] write a prolog program displaying an M*N grid of asterisk?

查看:19
本文介绍了编写一个显示 M*N 星号网格的序言程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个递归谓词 rectangle,这样 rectangle(M, N) 写出一个大小为 M x N 的实心矩形> 星号,即矩形中应该有 M 行和 N 列.例如:

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

到目前为止,我有语句 line 在一行上打印 N 个星号:

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:

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

并非每个 Prolog 都支持调用变量.例如,在我的旧 Prolog 解释器中,我会写 loop_n(P, N) :- forall(between(1, N, _), call(P)).

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

这篇关于编写一个显示 M*N 星号网格的序言程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆