获取列表的头部和尾部 [英] Getting the head and tail of a list

查看:45
本文介绍了获取列表的头部和尾部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如果我这样做了:

I know if I do:

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

我想要做的是在规则中获取列表的头部和尾部.这可能吗?我正在为递归调用设置基本情况,但现在如果它只是将 L3 作为第一个列表头和第二个列表头的附加返回,我会感到满意.我只是不确定如何获得头部和列表.

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].

至少现在是这样.

推荐答案

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]).

这篇关于获取列表的头部和尾部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆