本文介绍了递归Prolog谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在做一个项目,我想在 Prolog 中实现辅助谓词
i am currently working on a project and i want to implement helper predicate in Prolog
break_down(N, L)
其工作原理如下
?- break_down(1,L). L = [1] ; false. ?- break_down(4,L). L = [1, 1, 1, 1] ; L = [1, 1, 2] ; L = [1, 3] ; L = [2, 2] ; L = [4] ; false.对任何正整数 N 依此类推.
and so on for any positive integer N .
我已经尝试并实现了一个代码,它只生成第一个结果,我无法得到其余的结果,这是我的代码
i have tried and implemented a code which generates only the first result and i cannot get the rest of the results , and this is my code
break_down(1,[1]). break_down(N,L):- N>0, N1 is N-1, break_down(N1,L1), append(L1,[1],L).只生成第一个输出结果:
which generates only the first output result :
L = [1, 1, 1, 1] ;任何建议如何编辑我的代码以获得其余的?
any suggestion how to edit my code to get the rest ?
推荐答案这是一个使用普通整数算法和回溯的直接递归实现:
Here's a straight-forward recursive implementation using plain integer arithmetic and backtracking:
break_down(N,L) :- break_ref_down(N,1,L). % reference item is initially 1 break_ref_down(0,_,[]). break_ref_down(N,Z0,[Z|Zs]) :- between(Z0,N,Z), % multiple choices N0 is N-Z, break_ref_down(N0,Z,Zs). % pass on current item as reference示例查询:
?- break_down(8,Zs). Zs = [1,1,1,1,1,1,1,1] ; Zs = [1,1,1,1,1,1,2] ; Zs = [1,1,1,1,1,3] ; Zs = [1,1,1,1,2,2] ; Zs = [1,1,1,1,4] ; Zs = [1,1,1,2,3] ; Zs = [1,1,1,5] ; Zs = [1,1,2,2,2] ; Zs = [1,1,2,4] ; Zs = [1,1,3,3] ; Zs = [1,1,6] ; Zs = [1,2,2,3] ; Zs = [1,2,5] ; Zs = [1,3,4] ; Zs = [1,7] ; Zs = [2,2,2,2] ; Zs = [2,2,4] ; Zs = [2,3,3] ; Zs = [2,6] ; Zs = [3,5] ; Zs = [4,4] ; Zs = [8] ; false.更多推荐
递归Prolog谓词?
发布评论