首页 > 解决方案 > 编写 prolog star/1 程序

问题描述

我的任务是编写一个程序,给定一个包含 N 个整数的列表作为参数,打印 N 行,每行带有 X 个星,其中 X 在列表中的一个元素中。我得到了这个例子:

   ?-printstars([4,3,4,2]). 
    ****
    ***
    ****
    **

尝试使它不顺利。

foreach([]).
foreach([N|R]) :- stars(N), foreach(R).

解决方案仅产生:

?- stars(4).
ERROR: Unknown procedure: stars/1 (DWIM could not correct goal)

标签: prolog

解决方案


在这里使用递归是个好主意:

printstars([]).
printstars([0 | R]) :- nl, printstars(R), !.
printstars([A | B]) :- write("*"), K is A - 1, printstars([K | B]).

推荐阅读