prolog - 编写 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)
解决方案
在这里使用递归是个好主意:
printstars([]).
printstars([0 | R]) :- nl, printstars(R), !.
printstars([A | B]) :- write("*"), K is A - 1, printstars([K | B]).
推荐阅读
- javascript - 运行循环序列并随机停止,不仅是最后一个元素
- c# - 如何在开发/设计时将图像添加到 Resources.resx 文件中?
- javascript - 如何将项目添加到 localStorage JS?
- php - 单击它时复选框不起作用
- vue.js - 我正在寻找仅在输入 3 个字母时过滤的程序中的命令
- javascript - d3分组条形图不一致的项目对齐
- ffmpeg - 如何在 VMware Workstation 上使用物理计算机的 GPU?
- javascript - 单击按钮时表格会相互叠加
- python - Python中带有3个引号的多行
- html - 网页可以将自己作为规范网址吗?