在序言中生成从 N 到 1 的数字列表 [英] Generate list of numbers fron N to 1 in prolog

查看:32
本文介绍了在序言中生成从 N 到 1 的数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成从 N 到 1 的数字列表,而不使用任何内置谓词,例如 findall 或 numlist.我究竟做错了什么 ?

I am trying to generate a list of numbers from N to 1 without using any build-in predicated such as findall or numlist. What am I doing wrong ?

    pred(N,[H|T]):-  H is N, N1 is N-1, pred(N1,T).
    pred(1,[]).

我不断收到错误:超出全局堆栈

I keep getting ERROR: Out of global stack

推荐答案

切换子句的顺序.把第二个子句放在前面,否则它没有机会贡献(即停止),第一个子句继续倒计时到负无穷.

Switch the order of your clauses. Put the second clause first, otherwise it has no chance to contribute (i.e. to halt) and the first clause continues to count down to negative infinity.

当然更好的是通过在第一个子句中添加一个简单的测试作为第一个目标,使这两个子句互斥.

Of course even better is to make the two clauses mutually exclusive by adding a simple test as the first goal to your first clause.

这篇关于在序言中生成从 N 到 1 的数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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