首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >列表中的Prolog列表

列表中的Prolog列表
EN

Stack Overflow用户
提问于 2016-11-09 19:07:50
回答 1查看 385关注 0票数 1

当我试图创建一个包含多个子列表的列表时,我遇到了一些麻烦。我不明白为什么我的代码不能像预期的那样工作。

代码语言:javascript
复制
solves(_, _, 0, _).
solves(Length, List, Stopcond, NList):- length(NL, Length),
                         append([NL], List, NList),
                         write(NList), nl,
                         N is Stopcond-1, 
                         solves(Length, NList, N, NList2).

?- solves(3, [], 3, B).

我希望B是一个有三个子列表的列表,每个子列表都有三个实习生变量。当我写Nlist时,它显示:

代码语言:javascript
复制
 1. [[_G3207,_G3210,_G3213]]
 2. [[_G3222,_G3225,_G3228],[_G3207,_G3210,_G3213]]
 3. [[_G3237,_G3240,_G3243],[_G3222,_G3225,_G3228],[_G3207,_G3210,_G3213]]
 4. B = [[_G3207, _G3210, _G3213]] .

但我不明白为什么B成为列表中的最后一个元素。我想把它列在第3行的清单上,有人知道我为什么做错了什么吗?我对prolog很陌生。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-09 19:26:02

我想这就是你的本意

代码语言:javascript
复制
solves(_, List, 0, List).
solves(Length, List, Stopcond, NList2):- length(NL, Length),
                         append([NL], List, NList),
                         %write(NList), nl,
                         N is Stopcond-1, 
                         solves(Length, NList, N, NList2).

您的谓词试图做什么(暂时忽略3个元素子列表)?它将长度的列表附加到传递的第二个参数(列表)中。

如何递归地构造长度TL的列表,给出长度L的列表?用长度为1的列表追加长度L的列表,并尝试从新的长度列表L+1中构造长度TL-1的列表。作为基本情况,您知道要从长度TL列表中构造长度TL列表,只需按原样返回列表。

谓词返回一个更大的列表,该列表由长度为Length的更小的Stopcond列表组成。递归地说,长度更大的Stopcond列表是附加在更大长度Stopcond-1列表中的较小长度元素列表.大小写:大小为0的更大的列表只是一个空列表。

如果我们只考虑0而不是3元素子列表,

代码语言:javascript
复制
solves(FinalList, 0, FinalList). % The result of appending a list of length 0 to the given list is the given list itself.
solves(List, StopCond, FinalList):- % Appends A list of length StopCond to List
    Length1List = [0], % Create a list of length 1
    append( Length1List, List, LengthPlus1List),
    N is N-1,
    solves( LengthPlus1List, N, FinalList).

因为你是新来的,所以在每一行上写英文注释可能会有帮助。

代码语言:javascript
复制
% Base case: stopping condition satisfied. List is the final List we need
solves(_, List, 0, List). 

% Recursive case: We need to make one more list of length L and append/prepend it to List
solves(Length, List, Stopcond, NList2):- 
                         length(NL, Length), % Create smaller-list of length Length
                         append([NL], List, NList), % Append it to the list we're building up
                         %write(NList), nl,
                         N is Stopcond-1,  
                         solves(Length, NList, N, NList2). % Build Stopcond-1 more lists 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40514245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档