Prolog附加到列表中

时间:2017-12-19 13:40:09

标签: prolog

% Generator for natural numbers
isNatural(0).
isNatural(X) :-
  isNatural(Y),
  X is Y+1.

rangeToList(From, To, ResultList) :-
    isNatural(X),
    X > From, 
    X < To,
    % Add X to the ResultList
    appendTo(X, ResultList, ResultList),
    Tn is To - 1,
    % do the same with X to To-1
    rangeToList(From , Tn, ResultList).

% appendTo(+Number, +List, -NewList)
appendTo(Number, [], [Number]).
appendTo(Number, List, NewList) :-
    append(List, [Number], NewList).

如何将X附加到ResultList?每当appendTo从一开始就到达List = NewList这不是我的意图,因为我想将List[Number]合并到NewList

1 个答案:

答案 0 :(得分:2)

您的程序存在一些问题:如评论中所述“您无法重新分配Prolog变量。一旦ResultList被实例化,除非通过回溯”,否则无法重新实例化。此外,您需要rangeToList的基本案例在递归期间停止它。第三个问题:如果您编写X > From, X < To,程序将永远循环,因为您在每一步减少值To,因此,在某一时刻,From将等于To并且程序将循环(由于您编写isNatural/1的方式)。最后但不是列表,您需要在递归调用后调用appendTo/3(我建议您将此谓词转换为尾递归谓词,因此递归调用将是最后一次调用)。我修改了你的程序,但我认为这不是你想要获得的结果

isNatural(0).
isNatural(X) :-
  isNatural(Y),
  X is Y+1.

rangeToList(A,A,_).
rangeToList(From, To, ResultList) :-
    isNatural(X),
    X >= From, 
    X =< To,
    Tn is To - 1,
    rangeToList(From , Tn, ResultList1),
    appendTo(X, ResultList1, ResultList).

appendTo(Number, [], [Number]).
appendTo(Number, List, NewList) :-
    append(List, [Number], NewList).

?-rangeToList(1,3,L).
L = [2,2]

要获取实际列表,您需要更改生成数字的方式。 解决方案可能是:

rangeToList(A,A,[A]).
rangeToList(From, To, ResultList) :-
    From =< To,
    From1 is From + 1,
    rangeToList(From1 , To, ResultList1),
    appendTo(From, ResultList1, ResultList).

appendTo(Number, [], [Number]).
appendTo(Number, List, NewList) :-
    append(List, [Number], NewList).

?-rangeToList(1,4).
L = [3,2,1]