递归Prolog谓词?

编程入门 行业动态 更新时间:2024-10-22 09:47:53
本文介绍了递归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谓词?

本文发布于:2023-11-30 03:15:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648540.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   谓词   Prolog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!