Getting the head and tail of a list

☆樱花仙子☆ 提交于 2019-12-25 06:54:54

问题


I know if I do:

[H|T] = [a,b,c,d].
H = a,
T = [b,c,d].

What I'm trying to do is get the head and tail of a list inside a rule. Is this possible? I'm setting up base cases for a recursive call but for now I'd be satisfied if it just returned L3 as a append of the first list head and the second list head. I'm just not sure how I can get the head and list.

compose([], L1, L1).
compose(L2, [], L2).
compose([], [], []).
compose(L1, L2, L3) :-
        [H1|T1] = L1,
        [H2|T2] = L2,   
        append(H1, H2, L3).  

I've also tried doing below based on what I've seen online:

compose([], L1, L1).
compose(L2, [], L2).
compose([], [], []).
compose([H1|T1], [H2|T2], L3) :-
        append(H1, H2, L3).     

but the trace fails on the Call to this predicate.In a successful case I would like it to do the following:

compose([a,b,c], [d,e,f], L).
L = [a, d].

at the very least for now.


回答1:


compose([X|_],[Y|_], [X,Y]).

It is not more than that. Maybe you want to add cases for empty lists:

compose([], [], []).
compose([X|_], [], [X]).
compose([], [X|_], [X]).


来源:https://stackoverflow.com/questions/26952454/getting-the-head-and-tail-of-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!