深层列表中的最后一个元素

时间:2013-02-16 13:29:43

标签: prolog

因此,如果输入为 L = [1,[2,3,4],5] ,则输出应为 R = [4,5] 。 常规列表中最后一个元素的代码是

last([X],X].
last([H|T],X):-last(T,X).

2 个答案:

答案 0 :(得分:0)

这不是优雅的Prolog,但我认为它会做你想要的:

deeplast([L], X) :-
    deeplast(L, X).
deeplast([X], X) :-
    atomic(X).
deeplast([H|T], X) :-
    atomic(H),
    deeplast(T, X).
deeplast([H|T], X) :-
    compound(H),
    deeplast(H, Y),
    deeplast(T, Z),
    X = [Y, Z].

答案 1 :(得分:0)

这是彼得的anwers的略作编辑的版本:

deeplast([L], X) :-
    deeplast(L, X).

deeplast([X], X) :-
    atomic(X).

deeplast([H|T], X) :-
    atomic(H),
    deeplast(T, X).

deeplast([H|T], X) :-

    deeplast(H, Y),
    deeplast(T, Z),
    X = Z.


?- deeplast([1,[2,3],4,[5,[6,8]]],R).
   R = 8 
相关问题