如何构造长度为n的“链式”列表

时间:2014-08-18 12:35:12

标签: prolog

如何概括以下语句以构造长度为L的任何链式列表n

list(1,S1,S2,L) :-
  L = [[S1,S2]]].
list(2,S1,S2,L) :-
  L = [[S1,S3]],[S3,S2]]].
list(3,S1,S2,L) :-
  L = [[S1,S3]],[S3,S4]],[S4,S2]]].
list(4,S1,S2,L) :-
  L = [[S1,S3]],[S3,S4]],[S4,S5]],[S5,S2]]].
list(5,S1,S2,L) :-
  L = [[S1,S3]],[S3,S4]],[S4,S5]],[S5,S6],[S6,S2]]].

2 个答案:

答案 0 :(得分:4)

怎么样:

chain(N, S0, S, Ls) :-
    length(Ls, N),
    chain_(Ls, S0, S).

chain_([], S, S).
chain_([[S0,S1]|Ls], S0, S) :-
    chain_(Ls, S1, S).

或等效地,使用foldl/4

chain(N, S0, S, Ls) :-
    length(Ls, N),
    foldl(chain_, Ls, S0, S).

chain_([S0,S], S0, S).

示例查询:

?-  chain(3, S0, S, Ls).
Ls = [[S0, _G1584], [_G1584, _G1593], [_G1593, S]].

答案 1 :(得分:1)

list(1,S1,S2,[[S1,S2]]).
list(N,S1,S2,[[S1,S]|T]) :-
    N > 1,
    M is N-1,
    list(M,S,S2,T).

试验:

?- list(3, S0, S, Ls).
Ls = [[S0, _G2824], [_G2824, _G2833], [_G2833, S]]